﻿Option Explicit On

Imports System.Text
Imports System.IO
Imports Microsoft.Office
Imports System.Data
Imports System.ComponentModel
Imports Global_Visas_Business_Layer

Partial Public Class frmMainDisplay
    Private Enum EventView
        Company = 1
        Person = 2
        CaseId = 3
        Consultant = 4
        All = 5
        Combined = 6
    End Enum

    Private Enum ViewByStatus
        AllOpen = 1
        PreSale = 2
        Initiated = 3
        Closed = 4
        AllCases = 5
    End Enum

    Private Enum CaseTypes
        Candidate = 1
        Company = 2
    End Enum

    Private Enum ScreenGrids
        CaseSummary = 1
        InvoiceSummary = 2
    End Enum

    Public Enum PageTabs
        NotSet = 0
        Company = 1
        Person = 2
        Cases = 3
        Events = 4
        Accounts = 5
    End Enum

    Private _ActiveTab As PageTabs
    Private m_strCurrencyChar As String
    Private m_bCloseMe As Boolean = False

    Public Property ActiveTab() As PageTabs
        Get
            Return _ActiveTab
        End Get
        Set(ByVal value As PageTabs)
            _ActiveTab = value
        End Set
    End Property

    Public ReadOnly Property ActivePersonId() As Long
        Get
            'This is person that is being edited / viewed via the Person panel, not necessarily the active candidate in the case
            Dim tabItemFlag As Boolean = False
            For Each item As TabItem In TabControl1.Items
                If item.Name = "tabCompany" Then
                    tabItemFlag = True
                    Exit For
                Else
                    tabItemFlag = False
                End If
            Next
            If tabItemFlag = False Then
                Return GlobalCRM.CurrentCandidateID
            Else
                If Me.lvwPeopleList.SelectedItems.Count > 0 Then
                    Return Me.lvwPeopleList.SelectedItems(0).SubItems(0).Text
                Else
                    Return 0
                End If
            End If

        End Get

    End Property

    Public Sub frmMainDisplay_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        Try
            Dim MDI As New frmCRMMDI
            MDI.LoadMainPage()
            'Me.ToolTip1.ShowAlways = True

            'Me.ToolTip1.ReshowDelay = 10

            'ToolTip1.SetToolTip(Me.btnStage1, Me.btnStage1.Text)
            'ToolTip1.SetToolTip(Me.btnStage2, Me.btnStage2.Text)
            'ToolTip1.SetToolTip(Me.btnStage3, Me.btnStage3.Text)
            'ToolTip1.SetToolTip(Me.btnStage4, Me.btnStage4.Text)
            'ToolTip1.SetToolTip(Me.btnStage5, Me.btnStage5.Text)
            'ToolTip1.SetToolTip(Me.btnStage6, Me.btnStage6.Text)
            Me.RemoveHandlers()
            ''check whether the case is with credit controller
            'If ISWithCre5ditController(GlobalCRM.CurrentCaseID) Then
            '    If MsgBox("The case is with the credit controller. Would you wish to continue? ", MsgBoxStyle.YesNo, "CC") = MsgBoxResult.No Then
            '        'IDSearch = "The case search has been completed"
            '        lblCreditController.Visible = False
            '        Exit Sub
            '    Else
            '        lblCreditController.Visible = True
            '    End If
            'End If
            'Stop first case becoming active
            Me.ClearScreen()
            Me.grdCases.SelectedItems.Clear()
            Me.cmbEmailTo.SelectedIndex = 1
            If Cases.CurrentLockedCaseID <> 0 Then
                If Cases.UnLockCase(Cases.CurrentLockedCaseID, GlobalCRM.CurrentConID) = Cases.LockState.Unsuccessful Then
                    m_bCloseMe = True
                    Exit Sub
                End If
            End If

            If Cases.LockCase(GlobalCRM.CurrentCaseID, GlobalCRM.CurrentConID) = Cases.LockState.Unsuccessful Then
                m_bCloseMe = True
                Exit Sub
            End If


            If GlobalCRM.CurrentCompanyID > 0 Then

                Dim myData As DataTable

                myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.AllOpen, CaseTypes.Company))

                If myData.Rows.Count > 0 Then
                    'Display open cases
                    Global_Visas_Business_Layer.DataBinding.BindListView(myData, grdCases)

                    'Automatically selects first row, remove it.
                    Me.grdCases.SelectedItems.Clear()


                Else
                    'No open cases, so display all cases
                    myData.Dispose()
                    'Me.grdCases.DataSource = DB.GetSQLDataTable(Me.CaseListSQL(ViewByStatus.AllCases, CaseTypes.Company))
                    Me.radCaseAll.IsChecked = True
                End If

                ''Automatically select first case in the list
                'If GlobalCRM.CurrentCaseID = 0 Then
                '    If CType(Me.grdCases.DataSource, DataTable).Rows.Count > 0 Then
                '        GlobalCRM.CurrentCaseID = CType(Me.grdCases.DataSource, DataTable).Rows(0).Item("case_id")
                '    End If
                'Else
                '    'Remembered case id from history screen
                'End If

                'Me.grpPersonal.Width = 700
                'Me.grpContact.Left = Me.grpPersonal.Width + 25


            ElseIf GlobalCRM.CurrentCandidateID > 0 Then

                Dim myData As DataTable


                myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.AllOpen, CaseTypes.Candidate))
                If myData.Rows.Count > 0 Then
                    'Display open cases
                    Global_Visas_Business_Layer.DataBinding.BindListView(myData, Me.grdCases)

                Else
                    'No open cases, so display all
                    myData.Dispose()

                    'MG 17/08/07 This was commented out???
                    Global_Visas_Business_Layer.DataBinding.BindListView(CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.AllCases, CaseTypes.Candidate)), Me.grdCases)
                    Me.radCaseAll.IsChecked = True
                End If

                'Me.grpPersonal.Width = 300
                'Me.grpContact.Left = Me.grpPersonal.Width + 25

            End If

            'Automatically select first case in the list, but only if it's a private client
            If GlobalCRM.CurrentCaseID = 0 And GlobalCRM.CurrentCompanyID = 0 Then
                If Not IsNothing(Me.grdCases.DataContext) Then
                    'If CType(Me.grdCases.DataSource, DataTable).Rows.Count > 0 Then
                    Dim currentRow As DataRowView = CType(grdCases.Items(0), DataRowView)
                    GlobalCRM.CurrentCaseID = currentRow("caseid")
                    'End If
                End If
            Else
                'Remembered case id from history screen
            End If

            'Dim myStage As Cases.CaseStage = Cases.GetCaseStage(GlobalCRM.CurrentCaseID)
            'Dim myAccountsSummary As CommonSQL.AccountsSummary = CommonSQL.GetAccountsSummary(GlobalCRM.CurrentCaseID)
            'Dim myDocSummary As CommonSQL.DocumentsSummary = CommonSQL.GetDocStoreSummary(GlobalCRM.CurrentCaseID)

            Dim myCases As DataTable
            Dim myRow As DataRow
            Dim myNewRow As DataRow
            Dim CaseList As New DataTable

            m_strCurrencyChar = Global_Visas_Business_Layer.CommonDataFunctions.GetCurrencyCodeCharacter(GlobalCRM.CurrentCaseID)

            Me.lblCandidateID.Text = GlobalCRM.CurrentCandidateID
            'Me.lblCandidateID2.Text = GlobalCRM.CurrentCandidateID
            If GlobalCRM.CurrentCompanyID = 0 Then
                Me.lblCandidateName.Text = GlobalCRM.CurrentCandidateName
            Else
                Me.lblCandidateName.Text = GlobalCRM.CurrentCompanyName
            End If
            'Me.lblCandidateName2.Text = GlobalCRM.CurrentCandidateName
            Me.lblCandidateName3.Text = GlobalCRM.CurrentCandidateName
            Me.lblCandidateId3.Text = GlobalCRM.CurrentCandidateID


            If GlobalCRM.CurrentCandidateID > 0 Then

                Me.LoadPhoneNumbers(GlobalCRM.CurrentCandidateID)
                Me.LoadEmailAddresses(GlobalCRM.CurrentCandidateID)
                Me.LoadAddresses(GlobalCRM.CurrentCandidateID)

            Else
                Me.lvwEmailAddress.Items.Clear()
                Me.lvwPhoneNumbers.Items.Clear()
                Me.lvwAddresses.Items.Clear()
            End If



            'Me.EventViewChanged(Me.radEventPerson, New EventArgs)
            'Me.drpEventView.SelectedValue = GlobalCRM.CurrentCandidateID

            ' add 

            Dim dv As DataView = Me.grdCases.ItemsSource()


            myCases = dv.ToTable("myCasesTable")
            'myCases = CType(Me.grdCases.ItemsSource(), DataTable)

            With CaseList.Columns
                .Add(New DataColumn("casename", System.Type.GetType("System.String")))
                .Add(New DataColumn("caseid", System.Type.GetType("System.Int32")))
            End With

            If Not IsNothing(myCases) Then

                ' i don't know what this bit is doing, but it didn't like the fact I had changed the column names for the grdCases datagrid (in the sql)
                For Each myRow In myCases.Rows
                    myNewRow = CaseList.NewRow
                    myNewRow.Item("caseid") = myRow.Item("CaseID")
                    myNewRow.Item("casename") = myRow.Item("CaseID") & " / " & myRow.Item("Product") & " / " & myRow.Item("Status")
                    CaseList.Rows.Add(myNewRow)
                Next

                'For Each myRow In myCases.Rows
                '    myNewRow = CaseList.NewRow
                '    myNewRow.Item("caseid") = myRow.Item("case_id")
                '    myNewRow.Item("casename") = myRow.Item("case_id") & " / " & myRow.Item("product_name") & " / " & myRow.Item("casestage")
                '    CaseList.Rows.Add(myNewRow)
                'Next


            End If





            'Get candidate details

            Me.ShowCandidateDetails(GlobalCRM.CurrentCandidateID)


            'GblFunc_Populate_CaseStages(GlobalCRM.CurrentCaseID)

            If GlobalCRM.CurrentCompanyID = 0 Then
                'Not a corporate case, so remove company tab
                Me.TabControl1.Items.Remove(Me.tabCompany)
                'Don't allow company events
                Me.radEventCompany.IsEnabled = False
                Me.lblCon1.Visibility = False
                Me.lblContactId.Visibility = False
                Me.lblContactName.Visibility = False
                'Me.TabControl1.SelectedTab = Me.tabPeople ' SelectedIndex = 1
                Me.lvwPeopleList.Visibility = False
                Me.btnAddPersToComp2.Visibility = False
                Me.lblPrivateMessage.Visibility = True
                btnAddtoCompany.Visibility = True
                Me.grpRoleView.Visibility = False
                Dim accountCaseSummary, accountInvoiceSummary As DataTable
                accountCaseSummary = Accounts.CaseSummary(GlobalCRM.CurrentCandidateID, Accounts.AccountTypes.Individual)
                Global_Visas_Business_Layer.DataBinding.BindListView(accountCaseSummary, Me.grdCaseSummary)

                accountInvoiceSummary = Accounts.InvoiceSummary(GlobalCRM.CurrentCandidateID, Accounts.AccountTypes.Individual)
                Global_Visas_Business_Layer.DataBinding.BindListView(accountCaseSummary, Me.grdInvoiceSummary)

            Else

                'This is a corporate case, so populate company tab

                'Dim myComp As Company.CompanyInfo = Company.GetCompany(GlobalCRM.CurrentCompanyID)
                'Dim myCorpContact As CommonSQL.CorporateContact = CommonSQL.GetCorporateContact(GlobalCRM.CurrentCaseID)

                If IsNothing(Me.TabControl1.Items("tabCompany")) Then
                    Me.TabControl1.Items.Insert(0, Me.tabCompany)
                End If

                Me.LoadCompanyInfo()
                Dim subSidiaryList, corporateContacts, corporatePeople As DataTable
                'Dim sqlList As String
                'sqlList = CommonDataFunctions.SubsidiaryList(GlobalCRM.CurrentCompanyID)
                subSidiaryList = CommonDataFunctions.SubsidiaryList(GlobalCRM.CurrentCompanyID)
                DataBinding.BindListView(subSidiaryList, Me.lvwSubsidiary)

                ' sqlList = CommonSQL.GetCorporateContacts(GlobalCRM.CurrentCompanyID)
                corporateContacts = Company.GetCorporateContacts(GlobalCRM.CurrentCompanyID)
                DataBinding.BindListView(corporateContacts, Me.lvwContacts)
                'DataBinding.BindListView(CommonSQL.GetCorporateAddresses(.CompanyID), Me.lvwCoAddresses, True)
                Me.LoadCompanyAddresses()

                'sqlList = CommonDataFunctions.GetCorporatePeople(GlobalCRM.CurrentCompanyID, CommonSQL.CompanyPeopleView.All)
                corporatePeople = Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.All)
                DataBinding.BindListView(corporatePeople, Me.lvwPeopleList)

                '' krishan 
                'DataBinding.SelectListviewRow(Me.lvwPeopleList, GlobalCRM.CurrentCandidateID)

                'End With

                'Me.lblContactName.Text = myCorpContact.ContactName
                'Me.lblContactId.Text = myCorpContact.ContactID

                'Me.TabControl1.SelectedTab = Me.tabCase '.SelectedIndex = 0
                If Not Me.lvwPeopleList.SelectedIndex = -1 Then
                    Me.lvwPeopleList.SelectedIndex = 0
                End If


                Me.lvwPeopleList.Visibility = True
                Me.lblPrivateMessage.Visibility = False
                'btnAddtoCompany.Visibility = False
                RemoveHandler drpRoles.SelectionChanged, AddressOf drpRoles_SelectionChanged

                With Me.drpRoles
                    .DisplayMemberPath = "role_name"
                    .SelectedValuePath = "role_id"
                End With
                Global_Visas_Business_Layer.DataBinding.BindComboBox(Global_Visas_Business_Layer.CommonDataFunctions.RoleList(), Me.drpRoles)

                AddHandler drpRoles.SelectionChanged, AddressOf drpRoles_SelectionChanged

                Me.grpRoleView.Visibility = True

                Dim accountCaseSummary, accountInvoiceSummary As DataTable
                accountCaseSummary = Accounts.CaseSummary(GlobalCRM.CurrentCandidateID, Accounts.AccountTypes.Corporate)
                Global_Visas_Business_Layer.DataBinding.BindListView(accountCaseSummary, Me.grdCaseSummary)

                accountInvoiceSummary = Accounts.InvoiceSummary(GlobalCRM.CurrentCandidateID, Accounts.AccountTypes.Corporate)
                Global_Visas_Business_Layer.DataBinding.BindListView(accountCaseSummary, Me.grdInvoiceSummary)



            End If

            'Me.FormatGrids()
            'Me.AddFooterRow(Me.grdCaseSummary, ScreenGrids.CaseSummary)
            'Me.AddFooterRow(Me.grdInvoiceSummary, ScreenGrids.InvoiceSummary)

            'Me.ResizeControls()

            ' select appropriate tab
            If GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eCompany Then
                Me.TabControl1.SelectedItem = Me.tabCompany
            ElseIf GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.ePerson Then
                Me.TabControl1.SelectedItem = Me.tabPeople
            ElseIf GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eCase Then
                Me.TabControl1.SelectedItem = Me.tabCase
            ElseIf GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eEvent Then
                Me.TabControl1.SelectedItem = Me.tabEvent
            ElseIf GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eInvoice Then
                Me.TabControl1.SelectedItem = Me.tabAccount
            Else
                ' if nothing specified show people tab
                Me.TabControl1.SelectedItem = Me.tabPeople
            End If



            'If Me.ActiveTab <> PageTabs.NotSet Then
            '    Select Case Me.ActiveTab
            '        Case PageTabs.Person
            '            Me.TabControl1.SelectedTab = Me.tabPeople
            '    End Select
            'Else
            '    If GlobalCRM.CurrentCompanyID > 0 Then
            '        Me.TabControl1.SelectedTab = Me.tabCase 'Me.tabCompany
            '    Else
            '        Me.TabControl1.SelectedTab = Me.tabPeople
            '    End If
            'End If

            If GlobalCRM.CurrentCaseID > 0 Then
                'Sumathivinayak S - Tester wanted the defaulting for "All". hence defaulted from combined to 
                'All.
                Me.radEventAll.IsChecked = True
                'Me.radEventCombined.Checked = True
                Me.btnAddEventToCase.Content = "Add Event to Case"

                Me.EventViewChanged(Me.radEventAll, New EventArgs)
                'Me.drpEventView.SelectedValue = GlobalCRM.CurrentCaseID
            ElseIf GlobalCRM.CurrentCandidateID > 0 Then
                Me.radEventPerson.IsChecked = True
                Me.btnAddEventToCase.Content = "Add Event to Person"

                Me.EventViewChanged(Me.radEventPerson, New EventArgs)
                Me.drpEventView.SelectedValue = GlobalCRM.CurrentCandidateID
            End If


            Me.AddHandlers()

        Catch exc As Exception
            Global_Visas_Business_Layer.CommonFuncs.ErrorHandler(exc, "frmMainDisplay.Load")
        End Try
    End Sub

    Private Sub AddHandlers()

        AddHandler grdCases.SelectionChanged, AddressOf grdCases_SelectedRowsChanged

        AddHandler radCaseAll.Checked, AddressOf CaseViewChanged
        AddHandler radCaseClosed.Checked, AddressOf CaseViewChanged
        AddHandler radCaseInit.Checked, AddressOf CaseViewChanged
        AddHandler radCaseOpen.Checked, AddressOf CaseViewChanged
        AddHandler radCasePreSale.Checked, AddressOf CaseViewChanged

        AddHandler radEventAll.Checked, AddressOf EventViewChanged
        AddHandler radEventCase.Checked, AddressOf EventViewChanged
        AddHandler radEventCombined.Checked, AddressOf EventViewChanged
        AddHandler radEventCompany.Checked, AddressOf EventViewChanged
        AddHandler radEventConsultant.Checked, AddressOf EventViewChanged
        AddHandler radEventPerson.Checked, AddressOf EventViewChanged

    End Sub

    Private Sub CaseViewChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles radCaseAll.CheckedChanged, radCaseClosed.CheckedChanged, radCaseInit.CheckedChanged, radCaseOpen.CheckedChanged, radCasePreSale.CheckedChanged

        RemoveHandler grdCases.SelectionChanged, AddressOf grdCases_SelectedRowsChanged
        Dim DB As New Global_Visas_Data_Layer.DataAccess()
        If GlobalCRM.CurrentCompanyID > 0 Then
            Me.grdCases.ItemsSource = DB.GetSQLDataTable(Me.CaseListSQL(Me.CurrentCaseView, CaseTypes.Company))
        Else
            Me.grdCases.ItemsSource = DB.GetSQLDataTable(Me.CaseListSQL(Me.CurrentCaseView, CaseTypes.Candidate))
        End If

        AddHandler grdCases.SelectionChanged, AddressOf grdCases_SelectedRowsChanged

        'Me.SelectActiveCase()

    End Sub

    Private Function CurrentCaseView() As ViewByStatus

        If Me.radCaseAll.IsChecked Then
            Return ViewByStatus.AllCases
        ElseIf Me.radCaseClosed.IsChecked Then
            Return ViewByStatus.Closed
        ElseIf Me.radCaseInit.IsChecked Then
            Return ViewByStatus.Initiated
        ElseIf Me.radCaseOpen.IsChecked Then
            Return ViewByStatus.AllOpen
        ElseIf Me.radCasePreSale.IsChecked Then
            Return ViewByStatus.PreSale
        End If

    End Function

    Private Sub drpRoles_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles drpRoles.SelectionChanged
        'Dim sqlList As String = CommonDataFunctions.GetCorporatePeople(GlobalCRM.CurrentCompanyID, CommonDataFunctions.CompanyPeopleView.Category, CType(Me.drpRoles.SelectedValue, CommonDataFunctions.CompanyRoles))
        Dim corporatePeople As DataTable = Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.Category, CType(Me.drpRoles.SelectedValue, Company.CompanyRoles))
        DataBinding.BindListView(corporatePeople, Me.lvwPeopleList)
        'DataBinding.BindListView(CommonSQL.GetCorporatePeople(GlobalCRM.CurrentCompanyID, CommonSQL.CompanyPeopleView.Category, CType(Me.drpRoles.SelectedValue, CommonSQL.CompanyRoles)), Me.lvwPeopleList)

    End Sub

    Private Sub drpEventView_SelectionChnaged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpEventView.SelectionChanged

        Me.RefreshEventList()

        ' xxx this has been moved to the RefreshEventList() function
        ''Me.lvwEvents.Items.Clear()

        'If Me.radEventCase.Checked Then
        '    Me.EventSQL(EventView.CaseId, Me.drpEventView.SelectedValue)
        '    Me.lblViewingEvent.Text = "Viewing Events for: Case no. " & Me.drpEventView.Text  ' & " (" & Me.Combo_Events_DataToView.Column(1) & ")"
        'ElseIf Me.radEventPerson.Checked Then
        '    Me.EventSQL(EventView.Person, Me.drpEventView.SelectedValue)
        '    Me.lblViewingEvent.Text = "Viewing Events for: Person no. " & Me.drpEventView.SelectedValue & " (" & Me.drpEventView.Text & ")"
        'ElseIf Me.radEventConsultant.Checked Then
        '    Me.EventSQL(EventView.Consultant, Me.drpEventView.SelectedValue)
        '    Me.lblViewingEvent.Text = "Viewing Events for: Consultant no. " & Me.drpEventView.SelectedValue & " (" & Me.drpEventView.Text & ")"
        'ElseIf Me.radEventCombined.Checked Then
        '    Me.EventSQL(EventView.Combined, Me.drpEventView.SelectedValue)
        '    Me.lblViewingEvent.Text = "Viewing Events for: Case no. " & Me.drpEventView.Text  ' & " (" & Me.Combo_Events_DataToView.Column(1) & ")"
        'End If
        '' DataBinding.BindListView(CommonSQL.GetEventsSQL(Me.drpEventView.SelectedValue, GlobalCRM.CurrentConID, tasksevents.EventTypes.EventCase), Me.lvwEvents)

        'Me.lblMessage.Text = ""

    End Sub

    Public Sub RefreshEventList()

        'Me.lvwEvents.Items.Clear()

        If Me.radEventCase.IsChecked Then
            Me.EventSQL(EventView.CaseId, Me.drpEventView.SelectedValue)
            Me.lblViewingEvent.Content = "Viewing Events for: Case no. " & Me.drpEventView.Text  ' & " (" & Me.Combo_Events_DataToView.Column(1) & ")"
        ElseIf Me.radEventPerson.IsChecked Then
            Me.EventSQL(EventView.Person, Me.drpEventView.SelectedValue)
            Me.lblViewingEvent.Content = "Viewing Events for: Person no. " & Me.drpEventView.SelectedValue & " (" & Me.drpEventView.Text & ")"
        ElseIf Me.radEventConsultant.IsChecked Then
            Me.EventSQL(EventView.Consultant, Me.drpEventView.SelectedValue)
            Me.lblViewingEvent.Content = "Viewing Events for: Consultant no. " & Me.drpEventView.SelectedValue & " (" & Me.drpEventView.Text & ")"
        ElseIf Me.radEventAll.IsChecked Then
            'Sumathivinayak S - Testers wanted the defaulting for ALL. hence changed the defaulting as All.
            'It was combined before
            Me.EventSQL(EventView.All, GlobalCRM.CurrentCompanyID)
            'Me.EventSQL(EventView.All, Me.drpEventView.SelectedValue)
            Me.lblViewingEvent.Content = "Viewing Events for: Case no. " & Me.drpEventView.Text  ' & " (" & Me.Combo_Events_DataToView.Column(1) & ")"
        End If

        'DataBinding.BindListView(CommonSQL.GetEventsSQL(Me.drpEventView.SelectedValue, GlobalCRM.CurrentConID, tasksevents.EventTypes.EventCase), Me.lvwEvents)

        Me.lblMessage.Text = String.Empty

    End Sub

    Private Function EventSQL(ByVal EventType As EventView, ByVal LinkID As Long)


        Dim SQL As StringBuilder
        Dim LngContactID As Long, LngCandidateID As Long

        Select Case EventType

            Case EventView.Company

                'Get list of employees in company
                Dim Employees() As Long = Company.EmployeeList(LinkID)
                Dim i As Integer
                Dim EmployeeList As New StringBuilder

                If IsNothing(Employees) Then
                    Return String.Empty
                End If

                For i = Employees.GetLowerBound(0) To Employees.GetUpperBound(0)
                    EmployeeList.Append(Employees(i))
                    If i < Employees.GetUpperBound(0) Then
                        EmployeeList.Append(",")
                    End If
                Next

                SQL = New StringBuilder

                With SQL
                    .Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.Con_Name,")
                    .Append(" CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category, ")
                    .Append(" Case Event_LinkType when 3 then 'Company' ")
                    .Append(" when 2 then D_Person.Person_Fname + ' ' + D_Person.Person_Lname")
                    .Append(" else 'Case' End as LinkFor")

                    'From Clause
                    .Append(" FROM D_Event LEFT OUTER JOIN")
                    .Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")
                    .Append(" Left Outer Join D_Person on D_Event.Event_LinkID = D_Person.Person_ID")

                    'VB Code Defnition Where Clause (Item ID and Link Type defined above)
                    .Append(" WHERE ((D_Event.Event_LinkType = 3) And (D_Event.Event_LinkID = " & LinkID & "))")
                    If EmployeeList.ToString <> "" Then
                        .Append(" OR ((Event_LinkType = 2) AND (Event_LinkID in (" & EmployeeList.ToString & ")))")
                    End If

                    'Order By
                    .Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")
                End With

                Dim eventSummary As DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                Global_Visas_Business_Layer.DataBinding.BindListView(eventSummary, Me.lvwEvents)


            Case EventView.Person
                'By Person

                'Select clause
                SQL = New StringBuilder
                With SQL
                    .Append("SELECT     TOP 100 PERCENT Event_ID,  CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT, ")
                    .Append("     Event_Description, ISNULL(ConScheduled, ConEntered) AS con_name, CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")

                    'From Clause
                    .Append("    WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category, 'Person' AS Linkfor")
                    .Append(" FROM   dbo.V_Events WHERE     (Event_LinkType = 2) AND (Event_LinkID = " & LinkID & ")")

                    'VB Code Defnition Where Clause (Item ID and Link Type defined above)
                    .Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")

                    'Order By
                    '.Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")

                End With
                Dim eventSummary As DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                Global_Visas_Business_Layer.DataBinding.BindListView(eventSummary, Me.lvwEvents)
                'DataBinding.BindListView(SQL.ToString(), Me.lvwEvents)
                'Call GblFunc_Populate_List(StrSQL, "MainDisplay_Event_List", Form_Fm_MainDisplay.List_Events)

                'Me.Btn_Event_AddNew.Caption = "Add Event to Person"
                'Me.Btn_Event_AddNew.Enabled = True
                'Me.Lbl_Events_ViewingFor.Caption = "Viewing Events for: Person no. " & Me.Combo_Events_DataToView & " (" & Me.Combo_Events_DataToView.Column(1) & ")"

            Case EventView.CaseId
                'By Case

                'Select clause
                SQL = New StringBuilder
                With SQL
                    '.Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.Con_Name,")
                    '.Append(" CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category, Case Event_LinkType When 1 then 'Case' when 2 then 'Person' when 3 then 'Company' end as LinkFor")

                    ''From Clause
                    '.Append(" FROM D_Event LEFT OUTER JOIN")
                    '.Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                    ''VB Code Defnition Where Clause (Item ID and Link Type defined above)
                    '.Append(" WHERE (D_Event.Event_LinkType = 1) And (D_Event.Event_LinkID = " & LinkID & ")")

                    ''Order By
                    '.Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")


                    .Append("SELECT TOP 100 PERCENT Event_ID,  CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT, ")
                    .Append("   Event_Description, ISNULL(ConScheduled, ConEntered) AS con_name, ")
                    .Append("     CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")
                    .Append("  WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category, ")
                    .Append("  CASE Event_LinkType WHEN 1 THEN 'Case' WHEN 2 THEN 'Person' WHEN 3 THEN 'Company' END AS LinkFor")
                    .Append(" FROM  dbo.V_Events WHERE  (Event_LinkID = " & LinkID & ") AND (Event_LinkType = 1)")
                    .Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")


                End With
                Dim eventSummary As DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                Global_Visas_Business_Layer.DataBinding.BindListView(eventSummary, Me.lvwEvents)
                ' DataBinding.BindListView(.ToString, Me.lvwEvents)
                'Call GblFunc_Populate_List(StrSQL, "MainDisplay_Event_List", Form_Fm_MainDisplay.List_Events)

                'Me.Btn_Event_AddNew.Caption = "Add Event to Case"
                'Me.Btn_Event_AddNew.Enabled = True
                'Me.Lbl_Events_ViewingFor.Caption = "Viewing Events for: Case no. " & Me.Combo_Events_DataToView & " (" & Me.Combo_Events_DataToView.Column(1) & " : " & Me.Combo_Events_DataToView.Column(2) & ")"

            Case EventView.Consultant

                Dim myData As DataTable
                Dim myRow As DataRow
                Dim CaseList As New StringBuilder
                Dim PersonList As New StringBuilder

                'Everything entered by selected consultant

                'Need to assemble a list of all the Person and Case ref numbers for this company.

                'Cases first
                SQL = New StringBuilder
                With SQL
                    If GlobalCRM.CurrentCompanyID > 0 Then
                        .Append("Select Case_ID from  D_Case where Case_CompanyID = " & GlobalCRM.CurrentCompanyID)
                    Else
                        .Append("Select Case_ID from  D_Case where Case_CandidateID = " & GlobalCRM.CurrentCandidateID)
                    End If

                    myData = CommonDataFunctions.GetSQLDatatable(.ToString)
                End With

                For Each myRow In myData.Rows
                    CaseList.Append(myRow.Item("case_ID") & ",")
                Next

                myData.Dispose()

                'Now people
                'If Me.Page_Company.Visible = True Then
                SQL = New StringBuilder
                SQL.Append("Select Person_ID from  D_Person where Person_CompanyID = " & GlobalCRM.CurrentCompanyID) ' & Me.Txt_Company_ID)
                myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                For Each myRow In myData.Rows


                    PersonList.Append(myRow.Item("Person_ID") & ",")

                Next
                'Else
                'Rst.Close()
                'End If
                'Else
                'StrPersonList = Me.List_Person_People
                'End If

                'Now build the query for the event list (combo not needed for everything)

                'Select clause
                SQL = New StringBuilder
                With SQL
                    .Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.Con_Name,")
                    .Append("CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category, Case Event_LinkType When 1 then 'Case' when 2 then 'Person' when 3 then 'Company' end as LinkFor ")

                    'From Clause
                    .Append("FROM D_Event LEFT OUTER JOIN")
                    .Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                    'VB Code Defnition Where Clause (Item ID and Link Type defined above)

                    If GlobalCRM.CurrentCompanyID > 0 Then
                        .Append(" WHERE ( (D_EVent.Event_linktype =  3 AND D_Event.Event_LinkID = " & LinkID & ")")

                        If PersonList.ToString <> "" Then
                            PersonList = New StringBuilder("(" & Strings.Left(PersonList.ToString, Len(PersonList.ToString) - 1) & ")")
                            .Append(" OR (D_EVent.Event_linktype =  2 AND D_Event.Event_LinkID in " & PersonList.ToString & ")")
                        End If

                    Else
                        .Append(" WHERE ( (D_EVent.Event_linktype =  2 AND D_Event.Event_LinkID = " & LinkID & ")")
                    End If

                    If CaseList.ToString <> "" Then
                        CaseList = New StringBuilder("(" & Strings.Left(CaseList.ToString, Len(CaseList.ToString) - 1) & ")")
                        .Append(" OR (D_EVent.Event_linktype =  1 AND D_Event.Event_LinkID in " & CaseList.ToString & ")")
                    End If

                    .Append(") AND Event_EnteredBy = " & LinkID)

                    'Order By
                    .Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")

                End With
                Dim eventSummary As DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                Global_Visas_Business_Layer.DataBinding.BindListView(eventSummary, Me.lvwEvents)

                'DataBinding.BindListView(.ToString, Me.lvwEvents)
                'Me.Btn_Event_AddNew.Caption = "Add Event"
                'Me.Btn_Event_AddNew.Enabled = False
                'Me.Lbl_Events_ViewingFor.Caption = "Viewing Events for: All cases where entered by " & Me.Combo_Events_DataToView.Column(1)

            Case EventView.Combined
                'Case combined. All Events for selected case, plus those for the company (if present), candidate and contact (if present)

                Dim myData As DataTable

                'Get candidate ID
                SQL = New StringBuilder

                SQL.Append("Select Case_CandidateID, Case_ContactID from D_Case where Case_ID = " & LinkID)
                myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                If myData.Rows.Count > 0 Then


                    LngCandidateID = myData.Rows(0).Item("Case_CandidateID")
                    LngContactID = myData.Rows(0).Item("Case_ContactID")
                End If
                myData.Dispose()


                'Select clause
                SQL = New StringBuilder
                With SQL
                    .Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.Con_Name,")
                    .Append(" CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category,")

                    If GlobalCRM.CurrentCompanyID > 0 Then
                        .Append(" Case  ")
                        .Append("When Event_LinkType = 1 then 'Case' ")
                        .Append(" when Event_LinkType = 2 and Event_LinkID = " & LngCandidateID & " then 'Candidate' ")
                        .Append(" when Event_LinkType = 2 and Event_LinkID = " & LngContactID & " then 'Contact' ")
                        .Append(" when Event_LinkType = 2 then 'Person' ")
                        .Append("when Event_LinkType = 3 then 'Company' end as LinkFor")
                    Else
                        .Append(" Case  ")
                        .Append(" When Event_LinkType = 1 then 'Case' ")
                        .Append(" when Event_LinkType = 2 then 'Client' end as LinkFor")
                    End If

                    'From Clause
                    .Append(" FROM D_Event LEFT OUTER JOIN")
                    .Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                    'VB Code Defnition Where Clause (Item ID and Link Type defined above)
                    .Append(" WHERE (D_Event.Event_LinkType = 1) And (D_Event.Event_LinkID = " & LinkID & ")")

                    'Also get candidate events if candidate ID known
                    If LngCandidateID <> 0 Then
                        .Append(" OR (D_Event.Event_LinkType = 2) And (D_Event.Event_LinkID = " & LngCandidateID & ")")
                    End If

                    'is this a company case
                    If GlobalCRM.CurrentCompanyID > 0 Then

                        'Get company events as well
                        .Append(" OR (D_Event.Event_LinkType = 3) And (D_Event.Event_LinkID = " & GlobalCRM.CurrentCompanyID & ")")

                        'if we have a contact, get thier events as well
                        If LngContactID <> 0 Then
                            .Append(" OR (D_Event.Event_LinkType = 2) And (D_Event.Event_LinkID = " & LngContactID & ")")
                        End If
                    End If


                    'Order By
                    .Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")

                End With
                Dim eventSummary As DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                Global_Visas_Business_Layer.DataBinding.BindListView(eventSummary, Me.lvwEvents)
                'DataBinding.BindListView(.ToString, Me.lvwEvents)

            Case EventView.All

                Dim CaseList() As Long = Nothing
                Dim myData As DataTable
                Dim myRow As DataRow
                Dim i As Integer

                If GlobalCRM.CurrentCompanyID > 0 Then
                    'Need to assemble a list of all the Person and Case ref numbers for this company.

                    'Cases first

                    Dim PeopleList() As Long = Nothing

                    SQL = New StringBuilder
                    SQL.Append("Select Case_ID from D_Case where Case_CompanyID = " & GlobalCRM.CurrentCompanyID)

                    myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                    If IsNothing(myData) Then
                        Exit Function
                    End If

                    For Each myRow In myData.Rows
                        ReDim Preserve CaseList(i)
                        CaseList(i) = myRow.Item("case_id")
                        i = i + 1 'Harvey added this to fix problem
                    Next

                    myData.Dispose()

                    'Now people
                    SQL = New StringBuilder
                    SQL.Append("Select Person_ID from  D_Person where Person_CompanyID = " & GlobalCRM.CurrentCompanyID)

                    myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                    If IsNothing(myData) Then
                        Exit Function
                    End If

                    i = 0

                    For Each myRow In myData.Rows
                        ReDim Preserve PeopleList(i)
                        PeopleList(i) = myRow.Item("person_id")
                        i = i + 1 'Harvey added this to fix problem
                    Next

                    myData.Dispose()

                    'Now build the query for the event list (combo not needed for everything)

                    'Select clause
                    SQL = New StringBuilder
                    With SQL
                        '.Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.Con_Name,")
                        '.Append(" CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category, Case Event_LinkType When 1 then 'Case' when 2 then 'Person' when 3 then 'Company' end as LinkFor")

                        ''From Clause
                        '.Append(" FROM D_Event LEFT OUTER JOIN")
                        '.Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                        ''VB Code Defnition Where Clause (Item ID and Link Type defined above)
                        '.Append(" WHERE (D_EVent.Event_linktype =  3 AND D_Event.Event_LinkID = " & GlobalCRM.CurrentCompanyID & ")")
                        'If Not CaseList Is Nothing Then
                        '    If CaseList.Length > 0 Then
                        '        .Append(" OR (D_EVent.Event_linktype =  1 AND D_Event.Event_LinkID in " & CommonFunc.ArrayToCSV(CaseList) & ")")
                        '    End If
                        'End If
                        'If Not PeopleList Is Nothing Then
                        '    If PeopleList.Length > 0 Then
                        '        .Append(" OR (D_EVent.Event_linktype =  2 AND D_Event.Event_LinkID in " & CommonFunc.ArrayToCSV(PeopleList) & ")")
                        '    End If
                        'End If
                        ''Order By
                        '.Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")


                        .Append("SELECT     TOP 100 PERCENT Event_ID,  CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT, ")
                        .Append(" Event_Description, ISNULL(ConScheduled, ConEntered) AS con_name,  CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")
                        .Append(" WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category,  CASE Event_LinkType WHEN 1 THEN 'Case' WHEN 2 THEN 'Person' WHEN 3 THEN 'Company' END AS LinkFor")


                        'From Clause
                        .Append(" FROM         dbo.V_Events")

                        'VB Code Defnition Where Clause (Item ID and Link Type defined above)
                        .Append(" WHERE (Event_linktype =  3 AND Event_LinkID = " & GlobalCRM.CurrentCompanyID & ")")
                        If Not CaseList Is Nothing Then
                            If CaseList.Length > 0 Then
                                .Append(" OR (Event_linktype =  1 AND Event_LinkID in " & Global_Visas_Business_Layer.CommonFuncs.ArrayToCSV(CaseList) & ")")
                            End If
                        End If
                        If Not PeopleList Is Nothing Then
                            If PeopleList.Length > 0 Then
                                .Append(" OR (Event_linktype =  2 AND Event_LinkID in " & Global_Visas_Business_Layer.CommonFuncs.ArrayToCSV(PeopleList) & ")")
                            End If
                        End If
                        'Order By
                        .Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")

                    End With



                Else
                    'Private individual

                    'Only need to assemble case list
                    'Cases first
                    SQL = New StringBuilder
                    SQL.Append("Select Case_ID from D_Case where Case_CandidateID = " & ActivePersonId)

                    myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                    If IsNothing(myData) Then
                        Exit Function
                    End If

                    For Each myRow In myData.Rows
                        ReDim Preserve CaseList(i)
                        CaseList(i) = myRow.Item("case_id")
                        i = i + 1 'Harvey added this to fix problem
                    Next

                    myData.Dispose()

                    'Now build the query for the event list (combo not needed for everything)

                    'Select clause
                    SQL = New StringBuilder

                    With SQL
                        '.Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.Con_Name,")
                        '.Append(" CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category, Case Event_LinkType When 1 then 'Case' when 2 then 'Person' when 3 then 'Company' end as LinkFor")

                        ''From Clause
                        '.Append(" FROM D_Event LEFT OUTER JOIN")
                        '.Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                        ''VB Code Defnition Where Clause (Item ID and Link Type defined above)
                        '.Append(" WHERE (D_EVent.Event_linktype =  2 AND D_Event.Event_LinkID = " & Me.ActivePersonId & ")")

                        'If CaseList.Length > 0 Then
                        '    .Append(" OR (D_EVent.Event_linktype =  1 AND D_Event.Event_LinkID in " & CommonFunc.ArrayToCSV(CaseList) & ")")
                        'End If

                        ''Order By
                        '.Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")


                        .Append("SELECT TOP 100 PERCENT Event_ID, CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT,Event_Description ")
                        .Append(" , ISNULL(ConScheduled, ConEntered) AS con_name,  CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")

                        'From Clause
                        .Append(" WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category, CASE Event_LinkType WHEN 1 THEN 'Case' WHEN 2 THEN 'Person' WHEN 3 THEN 'Company' END AS LinkFor FROM dbo.V_Events WHERE (Event_LinkType = 2) AND (Event_LinkID = " & Me.ActivePersonId & ")")
                        '.Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                        'VB Code Defnition Where Clause (Item ID and Link Type defined above)
                        ' .Append(" WHERE (D_EVent.Event_linktype =  2 AND D_Event.Event_LinkID = " & Me.ActivePersonId & ")")

                        If CaseList.Length > 0 Then
                            .Append(" OR (Event_LinkType = 1) AND (Event_LinkID IN " & Global_Visas_Business_Layer.CommonFuncs.ArrayToCSV(CaseList) & ")")
                        End If

                        'Order By
                        .Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")



                        '.Append("SELECT TOP 100 PERCENT Event_ID, CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT,Event_Description ")
                        '.Append(", ISNULL(ConScheduled, ConEntered) AS con_name,  CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")
                        '.Append("  WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category, CASE Event_LinkType WHEN 1 THEN 'Case' WHEN 2 THEN 'Person' WHEN 3 THEN 'Company' END AS LinkFor FROM dbo.V_Events WHERE (Event_LinkType = 2) AND (Event_LinkID = " & Me.ActivePersonId & ") OR (Event_LinkType = 1) AND (Event_LinkID IN " & CommonFunc.ArrayToCSV(CaseList) & ")")
                        '.Append("  ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")
                        '.Append(" FROM dbo.V_Events WHERE   (Event_LinkType = 2) AND (Event_LinkID = " & Me.ActivePersonId & ") OR  (Event_LinkType = 1) AND (Event_LinkID IN " & CommonFunc.ArrayToCSV(CaseList) & ")")
                        '.Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")

                    End With


                End If
                Dim eventSummary As DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                Global_Visas_Business_Layer.DataBinding.BindListView(eventSummary, Me.lvwEvents)

                'DataBinding.BindListView(SQL.ToString, Me.lvwEvents)



                'Me.Btn_Event_AddNew.Caption = "Add Event to Case"
                'Me.Btn_Event_AddNew.Enabled = True
                'Me.Lbl_Events_ViewingFor.Caption = "Viewing Events for: Case no. " & Me.Combo_Events_DataToView & " (" & Me.Combo_Events_DataToView.Column(1) & " : " & Me.Combo_Events_DataToView.Column(2) & ")"

        End Select

        'Set up query for Event Dump
        'If StrSQL <> "" Then
        '    StrSQL = Right(StrSQL, Len(StrSQL) - 6)

        '    StrSQL = "Select Event_Message, " & StrSQL
        '    Call GblFunc_Create_Query(StrSQL, "Qry_SQL_Rpt_Maindisplay_EventDump")
        'End If

        Exit Function


    End Function

    Private Sub EventViewChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles radEventAll.CheckedChanged, radEventCase.CheckedChanged, radEventCombined.CheckedChanged, radEventCompany.CheckedChanged, radEventConsultant.CheckedChanged, radEventPerson.CheckedChanged

        RemoveHandler drpEventView.SelectionChanged, AddressOf drpEventView_SelectionChnaged

        'Me.lvwEvents.Items.Clear()

        'Select Case CType(CType(sender, RadioButton).Tag, EventView)

        ' if Case or Combined selected
        If radEventCase.IsChecked = True Or radEventCombined.IsChecked Then '    Case EventView.CaseId, EventView.Combined
            Me.btnAddEventToCase.IsEnabled = True

            Me.lblEventView.Content = "View Case"
            Me.btnAddEventToCase.Content = "Add Event to Case"
            Me.lblViewingEvent.Content = "Viewing Events for: Case not selected"

            If GlobalCRM.CurrentCompanyID > 0 Then

                With Me.drpEventView
                    .IsEnabled = True
                    .ItemsSource = Nothing
                    .DisplayMemberPath = "display_member"
                    .SelectedValuePath = "case_id"
                    .ItemsSource = Company.CompanyCases(GlobalCRM.CurrentCompanyID)
                    .SelectedIndex = -1
                End With
            Else

                With Me.drpEventView
                    .IsEnabled = True
                    .ItemsSource = Nothing
                    .DisplayMemberPath = "displayname"
                    .SelectedValuePath = "case_id"
                    .ItemsSource = CType(Cases.GetCaseList(GlobalCRM.CurrentCandidateID), IListSource).GetList

                    If .Items.Count > 0 Then
                        .SelectedIndex = 0
                    End If
                End With

            End If

            If Me.drpEventView.Items.Count > 0 Then
                Me.drpEventView.SelectedIndex = 0
                drpEventView_SelectionChnaged(Nothing, New System.EventArgs)

            Else
                Me.drpEventView.SelectedIndex = -1
            End If


            'Me.EventSQL(EventView.CaseId, GlobalCRM.CurrentCaseID)
            'Case EventView.Combined
            'Me.EventSQL(EventView.Combined)

            ' if All selected
        ElseIf radEventAll.IsChecked = True Then
            '            Case EventView.All
            Me.lblEventView.Content = String.Empty
            Me.btnAddEventToCase.IsEnabled = False
            Me.drpEventView.IsEnabled = False
            Me.drpEventView.ItemsSource = Nothing
            Me.EventSQL(EventView.All, GlobalCRM.CurrentCompanyID)

            ' if Company selected
            '           Case EventView.Company
        ElseIf radEventCompany.IsChecked = True Then
            Me.btnAddEventToCase.IsEnabled = False
            Me.lblEventView.Content = String.Empty
            Me.drpEventView.IsEnabled = False
            Me.drpEventView.ItemsSource = Nothing
            Me.EventSQL(EventView.Company, GlobalCRM.CurrentCompanyID)

            Me.lblViewingEvent.Content = "Viewing Events for: Company and Contacts"

            ' if Consultant selected
            'Case EventView.Consultant
        ElseIf radEventConsultant.IsChecked = True Then
            'Me.EventSQL(EventView.Consultant, GlobalCRM.CurrentConID)
            Me.lblEventView.Content = "View Consultant"
            Me.btnAddEventToCase.IsEnabled = False
            Me.lblViewingEvent.Content = "Viewing Events for: Consultant not selected"

            With Me.drpEventView
                .IsEnabled = True
                .ItemsSource = Nothing
                .DisplayMemberPath = "con_name"
                .SelectedValuePath = "con_id"
                .ItemsSource = CType(CommonDataFunctions.ConsultantList(True), IListSource).GetList
                .SelectedIndex = -1
            End With

            ' if Person selected
            'Case EventView.Person
        ElseIf radEventPerson.IsChecked = True Then

            Me.btnAddEventToCase.IsEnabled = True
            Me.lblEventView.Content = "View Person"
            Me.btnAddEventToCase.Content = "Add Event to Person"
            Me.lblViewingEvent.Content = "Viewing Events for: Person not selected"

            If GlobalCRM.CurrentCompanyID > 0 Then

                With Me.drpEventView
                    .IsEnabled = True
                    .ItemsSource = Nothing
                    .DisplayMemberPath = "person_name"
                    .SelectedValuePath = "person_id"
                    .ItemsSource = Company.CompanyPeople(GlobalCRM.CurrentCompanyID)
                    .SelectedIndex = -1
                End With
            Else
                With Me.drpEventView

                    ' xxx continue here - add Person's name to the drop down list

                    Dim myTable As New DataTable
                    myTable = CommonDataFunctions.GetSQLDatatable("Select Person_ID, Person_Fname + ' ' + Person_LName as PersonFullName From D_Person Where Person_ID = " & GlobalCRM.CurrentCandidateID)
                    .ItemsSource = CType(myTable, IListSource).GetList
                    .DisplayMemberPath = "PersonFullName"
                    .SelectedValuePath = "Person_ID"

                    'Dim myItem As New DataBinding.MyListItem
                    '.DataSource = Nothing
                    'myItem.ItemText = GlobalCRM.CurrentCandidateName.ToString
                    'myItem.ItemValue = GlobalCRM.CurrentCandidateID
                    '.Items.Add(myItem)
                    '.DisplayMember = "itemtext"
                    '.ValueMember = "itemvalue"
                    '.SelectedIndex = 0
                    'Me.drpEventView.Enabled = False

                    'Dim ci As Xceed.Editors.ComboBoxItem


                    ' Me.WinComboBox1.Items.Add(Xceed.Editors.ComboBoxItem("h", "1"))

                    '.Enabled = True
                    '.DataSource = Nothing
                    '.DisplayMember = "displayname"
                    '.ValueMember = "case_id"
                    '.DataSource = Cases.GetCaseList(GlobalCRM.CurrentCandidateID)

                    'If .Items.Count > 0 Then
                    '    .SelectedIndex = 0
                    'End If
                End With

                DataBinding.BindListView(People.GetPersonEvents(GlobalCRM.CurrentCandidateID), lvwEvents)

            End If


            'Me.EventSQL(EventView.Person, GlobalCRM.CurrentCandidateID)


        End If

        AddHandler drpEventView.SelectionChanged, AddressOf drpEventView_SelectionChnaged

    End Sub

    Private Function CaseListSQL(ByVal CaseView As ViewByStatus, ByVal CaseType As CaseTypes) As String

        Dim SQL As New StringBuilder

        With SQL
            .Append("SELECT D_Case.Case_ID as CaseID, Case Case_ActiveStatus when 1 then 'ON HOLD: ' else '' end + L_CaseStages.CaseStage_Title as Status,")
            '.Append("SELECT D_Case.Case_ID, Case Case_ActiveStatus when 1 then 'ON HOLD: ' else '' end + L_CaseStages.CaseStage_Title as CaseStage,")
            .Append("L_Products.Product_Name as Product, L_Consultant_Sales.Con_Name AS Consultant, L_Consultant_Case.Con_Name AS Caseworker, L_Consultant_Coordinator.Con_Name as Coordinator, ")
            .Append(" dbo.V_CaseWithPeople.Candidate as Candidate, ")
            '.Append("L_Products.Product_Name, L_Consultant_Sales.Con_Name AS Consultant, L_Consultant_Case.Con_Name AS Caseworker,")
            .Append("V_CaseWithPeople.Contact as Contact , CONVERT(VARCHAR(10),")
            .Append("D_Case.Case_DTStatus, 103) AS DateStatus FROM V_CaseWithPeople RIGHT OUTER JOIN D_Case ON V_CaseWithPeople.Case_ID = D_Case.Case_ID ")
            .Append("LEFT OUTER JOIN L_Consultant L_Consultant_Case ON D_Case.Case_ConCWID = L_Consultant_Case.Con_ID LEFT OUTER JOIN L_Consultant L_Consultant_Sales ON ")
            .Append("D_Case.Case_ConSaleID = L_Consultant_Sales.Con_ID LEFT OUTER JOIN L_CaseStages ON D_Case.Case_StatusID = L_CaseStages.CaseStage_Number LEFT OUTER JOIN L_Products ON D_Case.Case_ProductID = L_Products.Product_ID ")
            .Append("Left outer join L_Consultant L_Consultant_Coordinator on D_Case.Case_CoordinatorID = L_Consultant_Coordinator.Con_Id ")
            '.Append("Left join V_CaseContact on D_Case.Case_ID = V_CaseContact.Case_ID ")
            Select Case CaseView
                Case ViewByStatus.AllOpen
                    .Append("WHERE (D_Case.Case_StatusID < 1000) And ")
                Case ViewByStatus.AllCases
                    .Append("WHERE ")
                Case ViewByStatus.Closed
                    .Append("WHERE (D_Case.Case_StatusID >= 1000) And ")
                Case ViewByStatus.PreSale
                    .Append("WHERE (D_Case.Case_StatusID < 100) And ")
                Case ViewByStatus.Initiated
                    .Append("WHERE (D_Case.Case_StatusID between 100 and 999) And ")

            End Select
            Select Case CaseType
                Case CaseTypes.Candidate
                    .Append("(D_Case.Case_CandidateID = " & GlobalCRM.CurrentCandidateID & ") ")
                Case CaseTypes.Company
                    .Append("(D_Case.Case_companyID = " & GlobalCRM.CurrentCompanyID & ") ")

            End Select

            .Append("Order By D_Case.Case_ID Desc")
            Return .ToString
        End With

    End Function

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnClose.Click
        'Cases.UnLockCase(GlobalCRM.CurrentCaseID, GlobalCRM.CurrentConID)
        'Me.Close()
        Dim MDI As New frmCRMMDI
        MDI.LoadFrontPage()
        Me.Close()
    End Sub

    Private Sub RemoveHandlers()
        RemoveHandler grdCases.SelectionChanged, AddressOf grdCases_SelectedRowsChanged
    End Sub

    Private Sub grdCases_SelectedRowsChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles grdCases.SelectedRowsChanged

        'The selected case has change, update accordingly
        Me.SelectedCaseChanged()
    End Sub

    Private Sub SelectedCaseChanged()

        Dim objCase As Cases.CaseInfo
        '        Dim objCtrl As Control

        Try

            If Me.grdCases.SelectedItems.Count > 0 Then

                'Dim myStage As Cases.CaseStage
                Dim myDocSummary As CommonDataFunctions.DocumentsSummary
                Dim myAccountsSummary As Accounts.AccountsSummary
                Dim myCorpContact As Company.CorporateContact = Nothing

                Dim currentRowIndex As Integer = grdCases.SelectedIndex
                Dim currentRow As DataRowView = CType(grdCases.Items(currentRowIndex), DataRowView)

                GlobalCRM.CurrentCaseID = currentRow(0)
                ' xxx removed this to stop double logging of cases viewed
                'CommonFunc.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonFunc.DBIdTypes.CaseID)



                'myStage = Cases.GetCaseStage(GlobalCRM.CurrentCaseID)
                myDocSummary = CommonDataFunctions.GetDocStoreSummary(GlobalCRM.CurrentCaseID)
                myAccountsSummary = Accounts.GetAccountsSummary(GlobalCRM.CurrentCaseID)

                If GlobalCRM.CurrentCompanyID > 0 Then
                    myCorpContact = Company.GetCorporateContact(GlobalCRM.CurrentCaseID)
                End If

                'If Not IsNothing(myStage) Then
                '    Me.lblCaseStatus.Text = myStage.StageTitle
                '    Me.lblDateStatus.Text = Format(myStage.StageDateSet, "dd-MMM-yyyy")
                'End If
                Me.DisplayNewCaseStatus()

                If Not IsNothing(myDocSummary) Then
                    With myDocSummary
                        Me.lblNoDocOut.Content = .Required - .Received
                        Me.lblNoDocReq.Content = .Required
                        Me.lblNoDocStore.Content = .InDocStore
                    End With
                End If

                DisplayAccountsSummary(myAccountsSummary)

                Me.lblCandidateName2.Content = GlobalCRM.CurrentCandidateName
                Me.lblCandidateID2.Content = GlobalCRM.CurrentCandidateID

                If Not IsNothing(myCorpContact) Then
                    Me.lblContactName.Content = myCorpContact.ContactName
                    Me.lblContactId.Content = myCorpContact.ContactID
                End If

                GblFunc_Populate_CaseStages(GlobalCRM.CurrentCaseID)
                Me.LoadEventsTab()
                Me.LoadKeyDatesTab()
                Me.GblFunc_Populate_MFB(GlobalCRM.CurrentCaseID)

                Dim myCase As Cases.CaseInfo = Cases.GetCaseInfo(GlobalCRM.CurrentCaseID)

                Me.lblSubmitDate.Content = String.Empty

                If IsDate(myCase.SubmittedDate) Then
                    If myCase.SubmittedDate.Year > 1950 Then
                        Me.lblSubmitDate.Content = Format(myCase.SubmittedDate, "dd/MM/yyyy")
                    End If
                End If
                If IsDate(myCase.WrittenOffDate) Then
                    If myCase.WrittenOffDate.Year > 1950 Then
                        Me.lblWriteOffDate.Visibility = Windows.Visibility.Visible
                        Me.lblWrittenOff.Visibility = Windows.Visibility.Visible
                        Me.lblWriteOffDate.Content = Format(myCase.WrittenOffDate, "dd/MM/yyyy")
                    Else
                        Me.lblWriteOffDate.Visibility = Windows.Visibility.Hidden
                        Me.lblWrittenOff.Visibility = Windows.Visibility.Hidden
                        Me.lblWriteOffDate.Content = String.Empty
                    End If
                End If
                Me.lblDocReqDate.Content = DisplayDate(myCase.CriticalDate)
                Me.lblSubmitDate.Content = DisplayDate(myCase.SubmittedDate)
                Me.lblExtRef.Content = myCase.ExtRef
                Me.lblExpiry.Content = DisplayDate(myCase.ExpiryDate)
                Me.lblFTDate.Content = DisplayDate(myCase.FastTrackDate)

                ' sort out problem for new companies that have no people added
                If GlobalCRM.CurrentCandidateID > 0 Then
                    Dim itemTable As DataTable
                    itemTable = Global_Visas_Business_Layer.People.GetDependants(Global_Visas_Business_Layer.GlobalCRM.CurrentCandidateID)
                    DataBinding.BindListView(itemTable, Me.lvwDepend)
                End If

                'If Me.lvwDepend.Items.Count > 0 Then
                '    Me.grpDependants.Visible = True
                'End If

                Dim myParent As People.ParentInfo = People.GetParentPerson(GlobalCRM.CurrentCandidateID)

                If myParent.ParentId > 0 Then
                    Me.grpDependantOf.Visibility = Windows.Visibility.Visible
                    Me.lblDependOfName.Content = myParent.ParentName
                    Me.lblDependOfId.Content = myParent.ParentId
                Else
                    Me.lblDependOfName.Content = String.Empty
                    Me.lblDependOfId.Content = String.Empty
                    Me.grpDependantOf.Visibility = Windows.Visibility.Hidden
                End If

                Me.TabControl2.IsEnabled = True

                Me.btnEditCase.IsEnabled = True
                Me.btnSend.IsEnabled = True
                Me.btnInbox.IsEnabled = True
                Me.btnStockLetters.IsEnabled = True
                Me.btnAddCaseEvent.IsEnabled = True
                Me.btnViewCaseEvents.IsEnabled = True
                Me.btnAddCFF.IsEnabled = True
                Me.btnFileAudit.IsEnabled = True

                If Global_Visas_Business_Layer.CommonFuncs.WriteOffAccess(GlobalCRM.CurrentConID) = 1 Then
                    Me.btnCreditController.IsEnabled = True
                    'Me.btnRevertWriteOff.Enabled = True

                    'Me.btnEmailEvents.Enabled = True
                Else
                    Me.btnCreditController.IsEnabled = False
                    'Me.btnRevertWriteOff.Enabled = False
                    'Me.btnEmailEvents.Enabled = False
                End If
                If Global_Visas_Business_Layer.CommonFuncs.RevertWriteOffAccess(GlobalCRM.CurrentConID) = 1 Then

                    Me.btnRevertWriteOff.IsEnabled = True
                    'Me.btnEmailEvents.Enabled = True
                Else

                    Me.btnRevertWriteOff.IsEnabled = False
                    'Me.btnEmailEvents.Enabled = False
                End If

            End If
            'check whether the case is with credit controller
            If GlobalCRM.CreditControllerCaseID <> GlobalCRM.CurrentCaseID Then
                If Global_Visas_Business_Layer.CommonFuncs.ISWithCreditController(GlobalCRM.CurrentCaseID) Then
                    'MsgBox("The case is with the credit controller. Please do not work with this case ", MsgBoxStyle.Critical, "CC")
                    'IDSearch = "The case search has been completed"
                    'lblCreditController.Visible = False
                    'Exit Sub
                    'MsgBox("Case is with credit controller. Please do not work on this case", MsgBoxStyle.Critical, "CreditController")
                    Dim messagBox As New frmMessageBox()
                    messagBox.ShowDialog()
                    'display message box - 
                    GlobalCRM.CreditControllerCaseID = GlobalCRM.CurrentCaseID
                    lblCreditController.Content = "Case with credit controller. Stop working on this case"
                    lblCreditController.Visibility = Windows.Visibility.Visible

                Else
                    lblCreditController.Content = String.Empty
                    lblCreditController.Visibility = Windows.Visibility.Hidden
                    GlobalCRM.CreditControllerCaseID = GlobalCRM.CurrentCaseID
                End If
            End If

            If GlobalCRM.WrittenOffCaseID <> GlobalCRM.CurrentCaseID Then
                If Global_Visas_Business_Layer.CommonFuncs.ISCaseWrittenOff(GlobalCRM.CurrentCaseID) Then
                    'MsgBox("The case is with the credit controller. Please do not work with this case ", MsgBoxStyle.Critical, "CC")
                    'IDSearch = "The case search has been completed"
                    'lblCreditController.Visible = False
                    'Exit Sub
                    'MsgBox("Case is with credit controller. Please do not work on this case", MsgBoxStyle.Critical, "CreditController")
                    Dim msgWriteBox As New frmMessageBoxWriteOff
                    msgWriteBox.ShowDialog()
                    'display message box - 
                    GlobalCRM.WrittenOffCaseID = GlobalCRM.CurrentCaseID
                    lblCreditController.Content = "Case has been written Off. Stop working on this case"
                    lblCreditController.Visibility = Windows.Visibility.Visible

                Else
                    lblCreditController.Content = String.Empty
                    lblCreditController.Visibility = Windows.Visibility.Hidden
                    GlobalCRM.WrittenOffCaseID = GlobalCRM.CurrentCaseID
                End If
            End If
            'Sumathivinayak S 10/02/2009 Add the payment plan here
            'Commented 12/2/2009 as this is affecting the CSMs. Only when a case is initiated, this should popup.

            'Dim CaseStatusid As Long = CommonFunc.GetCaseStatus(GlobalCRM.CurrentCaseID)
            'If CaseStatusid >= 100 And CaseStatusid < 1000 Then
            '    If CommonFunc.GetCasePaymentPlan(GlobalCRM.CurrentCaseID) = 0 Then
            '        frmPaymentPlan.ShowDialog()
            '    End If
            'End If

            Try


                'ToolTip1.SetToolTip(Me.btnStage1, Me.btnStage1.Text)
                'ToolTip1.SetToolTip(Me.btnStage2, Me.btnStage2.Text)
                'ToolTip1.SetToolTip(Me.btnStage3, Me.btnStage3.Text)
                'ToolTip1.SetToolTip(Me.btnStage4, Me.btnStage4.Text)
                'ToolTip1.SetToolTip(Me.btnStage5, Me.btnStage5.Text)
                'ToolTip1.SetToolTip(Me.btnStage6, Me.btnStage6.Text)
            Catch ex As Exception

            End Try
        Catch ex As Exception
            Global_Visas_Business_Layer.CommonFuncs.ErrorHandler(ex, "frmMainDisplay.SelectedCaseChange")
        Finally
            objCase = Nothing
        End Try

    End Sub

    Private Function DisplayDate(ByVal dte As Date) As String
        If dte = DateSerial(1900, 1, 1) Or dte = TimeSerial(0, 0, 0) Then
            Return ""
        Else
            Return dte.ToShortDateString
        End If
    End Function

    Public Function GblFunc_Populate_MFB(ByVal LngCaseID As Long) As Integer

        Dim IntGroup As Integer
        Dim IntAssSLS As Integer
        Dim SQL As New StringBuilder
        Dim myButton As Button
        Dim DB As New Global_Visas_Data_Layer.DataAccess()

        Me.MFB1.Visibility = Windows.Visibility.Hidden
        Me.MFB2.Visibility = Windows.Visibility.Hidden
        Me.MFB3.Visibility = Windows.Visibility.Hidden
        Me.MFB4.Visibility = Windows.Visibility.Hidden
        Me.MFB5.Visibility = Windows.Visibility.Hidden
        Me.MFB6.Visibility = Windows.Visibility.Hidden
        Me.MFB7.Visibility = Windows.Visibility.Hidden
        Me.MFB8.Visibility = Windows.Visibility.Hidden
        Me.MFB9.Visibility = Windows.Visibility.Hidden

        If GlobalCRM.CurrentCaseID = 0 Then
            Exit Function
        End If

        'Before getting buttons, check for assessing auth SLS as if not present will need to diable certain buttons later

        Dim myData As DataTable
        Dim myRow As DataRow

        With SQL
            .Append("SELECT L_AssessingAuths.Assessingauth_SLSID")
            .Append(" FROM D_Case INNER JOIN")
            .Append(" D_Person ON D_Case.Case_CandidateID = D_Person.Person_ID INNER JOIN")
            .Append(" L_SkilledOcc ON D_Person.Person_SkilledOccID = L_SkilledOcc.SkilledOcc_ID INNER JOIN")
            .Append(" L_AssessingAuths ON L_SkilledOcc.SkilledOcc_AuthID = L_AssessingAuths.AssessingAuth_ID")
            .Append(" WHERE (D_Case.Case_ID = " & GlobalCRM.CurrentCaseID & ")")
        End With

        If DB.GetSQLScalar(SQL.ToString) <> 0 Then
            IntAssSLS = 1
        End If

        'Get the Group for this case
        IntGroup = Global_Visas_Business_Layer.CommonDataFunctions.GblFunc_Get_Dataset(GlobalCRM.CurrentCaseID, 2) 'mfb group

        If IntGroup = 0 Then
            'Nothing found, probably no product or product type, leave MFB blank
            Exit Function
        End If

        Dim myCase As Cases.CaseInfo = Cases.GetCaseInfo(GlobalCRM.CurrentCaseID)

        'Now know the current stage and the group, so begin to populate

        'Get relevent entries based on group and current stage

        SQL = New StringBuilder

        With SQL
            .Append("SELECT I_MFB.MFB_ID, I_MFB.MFB_Title, I_MFBLinks.MFBLink_Position")
            .Append(" FROM I_MFB INNER JOIN I_MFBLinks ON I_MFB.MFB_ID = I_MFBLinks.MFBLink_MFBID")

            .Append(" WHERE (I_MFBLinks.MFBLink_GroupID = " & IntGroup & ") ")

            'Check for correct customer type
            If GlobalCRM.CurrentCompanyID = 0 Then
                'Individual
                .Append(" AND (I_MFBLInks.MFBLink_CustomerType = 0 Or I_MFBLInks.MFBLink_CustomerType = 1)")
            Else
                'Company
                .Append(" AND (I_MFBLInks.MFBLink_CustomerType = 0 Or I_MFBLInks.MFBLink_CustomerType = 2)")
            End If

            'Check System Version
            .Append(" AND (I_MFBLInks.MFBLink_SystemVersionActive  < = " & GlobalCRM.SysVersion & " )")
            .Append(" AND (I_MFBLInks.MFBLink_SystemVersionDisable > " & GlobalCRM.SysVersion & " OR I_MFBLinks.MFBLink_SystemVersionDisable = 0)")

            .Append(" AND (")
            .Append(" (I_MFBLinks.MFBLink_StageStart <= " & myCase.CaseStatusId & " AND I_MFBLinks.MFBLink_StageEnd > " & myCase.CaseStatusId & ")")
            .Append(" OR ")
            .Append(" (I_MFBLinks.MFBLink_StageStart = 0 AND I_MFBLinks.MFBLink_StageEnd > " & myCase.CaseStatusId & ")")
            .Append(" OR ")
            .Append(" (I_MFBLinks.MFBLink_StageStart <= " & myCase.CaseStatusId & " AND I_MFBLinks.MFBLink_StageEnd = 0)")
            .Append(" OR ")
            .Append(" (I_MFBLinks.MFBLink_StageStart = 0 AND I_MFBLinks.MFBLink_StageEnd = 0)")
            .Append(" )")
        End With

        myData = DB.GetSQLDataTable(SQL.ToString)

        If IsNothing(myData) Then
            'Error State
            MsgBox("Call failed when polling for buttons", MsgBoxStyle.Critical)
            Exit Function
        End If

        If myData.Rows.Count = 0 Then
            myData.Dispose()
            'No buttons for this product/stage combo!
            Exit Function
        End If

        'Set the captions and make the buttons visible
        For Each myRow In myData.Rows

            For Each currentButton As FrameworkElement In grdTabCase.Children()
                If currentButton.GetType() Is GetType(System.Windows.Controls.Button) Then
                    If currentButton.Name = "MFB" & myRow.Item("MFBLink_Position") Then
                        myButton = currentButton
                    End If
                End If
            Next
            If myRow.Item("MFB_ID") = 8 Then
                If Not myCase.OnHold Then
                    myButton.Content = "Put case on hold"
                Else
                    myButton.Content = "Take case off hold"
                End If

            Else
                myButton.Content = myRow.Item("MFB_Title")
            End If

            If myRow.Item("MFB_ID") = 7 Then
                'Assessing auth SLS button, only switch on if there is an SLS available for this case
                If IntAssSLS = 1 Then
                    myButton.Visibility = Windows.Visibility.Visible
                End If
            Else
                myButton.Visibility = Windows.Visibility.Visible
            End If


        Next

        myData.Dispose()

    End Function

    Private Sub LoadEventsTab()
        Dim itemTable As DataTable
        itemTable = Global_Visas_Business_Layer.Cases.GetCaseEvents(Global_Visas_Business_Layer.GlobalCRM.CurrentCaseID, Global_Visas_Business_Layer.GlobalCRM.CurrentCandidateID)
        DataBinding.BindListView(itemTable, Me.lvwEventsTab)
        lblEventTab.Content = String.Empty
    End Sub

    Private Sub LoadKeyDatesTab()
        Dim itemTable As DataTable
        itemTable = Global_Visas_Business_Layer.Cases.GetKeyDates(Global_Visas_Business_Layer.GlobalCRM.CurrentCaseID)
        DataBinding.BindListView(itemTable, Me.lvwKeyDates)
    End Sub

    Public Function GblFunc_Populate_CaseStages(ByVal CaseID As Long) As Boolean


        Dim myData As DataTable
        Dim SQL As StringBuilder
        Dim IntProductID As Integer, IntStageID As Integer, IntDiagram As Integer
        Dim IntBtn As Integer, IntCtype As Integer
        Dim myRow As DataRow
        Dim myButton As Button
        Dim DB As New Global_Visas_Data_Layer.DataAccess()
        Me.btnStage1.Visibility = False
        Me.btnStage2.Visibility = False
        Me.btnStage3.Visibility = False
        Me.btnStage4.Visibility = False
        Me.btnStage5.Visibility = False
        Me.btnStage6.Visibility = False


        'If IsCo = 1 Then
        ' IntCtype = 2
        ' Else
        If GlobalCRM.CurrentCompanyID > 0 Then
            IntCtype = 2
        Else
            IntCtype = 1
        End If
        'End If

        If CaseID = 0 Then
            'No case, clear the form

            IntBtn = 1

            'Me.btnStage1.Visible = False
            'Me.btnStage2.Visible = False
            'Me.btnStage3.Visible = False
            'Me.btnStage4.Visible = False
            'Me.btnStage5.Visible = False
            'Me.btnStage6.Visible = False

            Return True
            Exit Function
        End If

        'Get product and stage details from the case
        SQL = New StringBuilder
        With SQL
            SQL.Append("Select Case_StatusID, Case_ProductID from D_Case where Case_Id = " & CaseID)
            myData = DB.GetSQLDataTable(.ToString)
        End With

        If IsNothing(myData) Then
            Exit Function
        End If

        If myData.Rows.Count = 0 Then
            Exit Function
        End If



        IntProductID = myData.Rows(0).Item("Case_ProductID")
        IntStageID = myData.Rows(0).Item("Case_StatusID")

        myData.Dispose()

        If IntProductID = 0 Then
            'No prodcut, use no product diagram
            IntDiagram = 2
        Else
            IntDiagram = Global_Visas_Business_Layer.CommonDataFunctions.GblFunc_Get_Dataset(CaseID, 1)
        End If

        If IntDiagram = 0 Then IntDiagram = 2

        'Now know the current stage and the diagram its within, so begin to populate

        'Find out which advance buttons are needed
        SQL = New StringBuilder
        With SQL
            .Append("SELECT L_StageLinks.StageLink_Desc, L_StageLinks.StageLink_ToID, L_StageLinks.StageLink_Position, L_StageLinks.StageLink_Admin ")
            .Append("FROM L_StageLinks ")
            .Append("WHERE (L_StageLinks.StageLink_DiagramID = " & IntDiagram & ") ")
            .Append(" And (L_StageLinks.StageLink_FromID = " & IntStageID & ")")
            .Append(" And (L_StageLinks.StageLink_CustomerType in (0, " & IntCtype & "))")
            myData = DB.GetSQLDataTable(.ToString)
        End With

        If Not myData Is Nothing Then

            If myData.Rows.Count = 0 Then
                myData.Dispose()
                'No links at all, do nothing
                Return True
                Exit Function
            End If
        Else
            Exit Function
        End If



        'Set the captions and make the buttons visible


        For Each myRow In myData.Rows

            'check for security
            If myRow.Item("StageLink_Admin") <> 0 Then
                If myRow.Item("StageLink_Admin") = 1 Then

                    For Each currentControl As FrameworkElement In grdStatus.Children

                        If currentControl.GetType() Is GetType(System.Windows.Controls.Button) Then
                            If currentControl.Name = "btnStage" & myRow.Item("StageLink_Position") Then
                                myButton = currentControl
                                myButton.Content = myRow.Item("stagelink_desc")
                                myButton.Visibility = Windows.Visibility.Visible
                            End If
                        End If
                    Next


                Else
                    'Admin only, dont make available
                    For Each currentControl As FrameworkElement In grdStatus.Children

                        If currentControl.GetType() Is GetType(System.Windows.Controls.Button) Then
                            If currentControl.Name = "btnStage" & myRow.Item("StageLink_Position") Then
                                myButton = currentControl
                                'myButton.Content = myRow.Item("stagelink_desc")
                                myButton.Visibility = Windows.Visibility.Visible
                            End If
                        End If
                    Next

                End If
            Else
                For Each currentControl As FrameworkElement In grdStatus.Children

                    If currentControl.GetType() Is GetType(System.Windows.Controls.Button) Then
                        If currentControl.Name = "btnStage" & myRow.Item("StageLink_Position") Then
                            myButton = currentControl
                            myButton.Content = myRow.Item("stagelink_desc")
                            myButton.Visibility = Windows.Visibility.Visible
                        End If
                    End If
                Next

            End If

            If myRow.Item("StageLink_ToID") = 999 Then 'SLA awaiting payment
                'If Form_Fm_MainDisplay.Page_Company.Visible = False Or Form_Fm_MainDisplay.Txt_Company_AccountType <> "SLA" Then
                If GlobalCRM.CurrentCompanyID = 0 Then

                    myButton.Visibility = Windows.Visibility.Hidden
                    'End If
                Else
                    'Hide if not SLA
                    If Company.GetAccountType(GlobalCRM.CurrentCompanyID) <> 2 Then
                        myButton.Visibility = Windows.Visibility.Hidden
                    End If

                End If
            End If


        Next

        myData.Dispose()

        Return True


    End Function

    Public Sub DisplayAccountsSummary(ByVal myAccountsSummary As Accounts.AccountsSummary)
        If Not IsNothing(myAccountsSummary) Then
            With myAccountsSummary
                Me.lblQuoteNet.Content = Format(.QuoteNet, m_strCurrencyChar & "0.00")
                Me.lblQuoteGross.Content = Format(.QuoteGross, m_strCurrencyChar & "0.00")
                Me.lblInvoiceNet.Content = Format(.InvoicedNet, m_strCurrencyChar & "0.00")
                Me.lblInvoiceGross.Content = Format(.InvoicedGross, m_strCurrencyChar & "0.00")
                Me.lblPayments.Content = Format(.Payments, m_strCurrencyChar & "0.00")
                Me.lblBalance.Content = Format(.Balance, m_strCurrencyChar & "0.00")
            End With
        End If
    End Sub

    Private Sub DisplayNewCaseStatus(Optional ByVal EditGrid As Boolean = False)

        Dim myStage As Cases.CaseStage = Cases.GetCaseStage(GlobalCRM.CurrentCaseID)

        If Not IsNothing(myStage) Then
            If myStage.ActiveStatus <> 1 Then
                Me.lblCaseStatus.Content = myStage.StageTitle
            Else
                Me.lblCaseStatus.Content = "ON HOLD: " & myStage.StageTitle
            End If
            Me.lblDateStatus.Content = Format(myStage.StageDateSet, "dd-MMM-yyyy")
        End If

        If EditGrid Then

            'Find data in grid and edit row, rather than reloading all of it.
            'Dim myRow As Xceed.Grid.DataRow

            'For Each myRow In Me.grdCases.DataRows
            '    If myRow.Cells("CaseID").Value = GlobalCRM.CurrentCaseID Then
            '        myRow.Cells("Status").Value = Me.lblCaseStatus.Text
            '        myRow.Cells("DateStatus").Value = Format(myStage.StageDateSet, "dd/MM/yyyy")
            '        Exit For
            '    End If
            'Next
        End If


    End Sub

    Private Sub ClearScreen()
        ' clear all details from last case viewed

        'Clear dependants
        Me.lblDependOfId.Content = String.Empty
        Me.lblDependOfName.Content = String.Empty
        Me.grpDependantOf.Visibility = False
        'Me.lvwDepend.Items.Clear()
        'Me.grpDependants.Visible = False

        'Clear Finance tab
        Me.lblQuoteNet.Content = String.Empty
        Me.lblQuoteGross.Content = String.Empty
        Me.lblInvoiceNet.Content = String.Empty
        Me.lblInvoiceGross.Content = String.Empty
        Me.lblPayments.Content = String.Empty
        Me.lblBalance.Content = String.Empty

        'Case Status
        Me.lblCaseStatus.Content = String.Empty
        Me.lblDateStatus.Content = String.Empty

        'Docstore
        Me.lblNoDocStore.Content = String.Empty
        Me.lblNoDocReq.Content = String.Empty
        Me.lblNoDocOut.Content = String.Empty

        'Events
        Me.lvwEventsTab.Items.Clear()
        Me.lblEventTab.Content = String.Empty

        'Key dates
        Me.lvwKeyDates.Items.Clear()

        Me.lblCandidateID2.Content = String.Empty
        Me.lblCandidateName2.Content = String.Empty
        Me.lblContactId.Content = String.Empty
        Me.lblContactName.Content = String.Empty

        Me.TabControl2.IsEnabled = False


        Me.btnEditCase.IsEnabled = False

        Me.btnSend.IsEnabled = False
        Me.btnInbox.IsEnabled = False
        Me.btnStockLetters.IsEnabled = False
        Me.btnAddCaseEvent.IsEnabled = False
        Me.btnViewCaseEvents.IsEnabled = False
        Me.btnAddCFF.IsEnabled = False
        Me.btnFileAudit.IsEnabled = False
        Me.btnCreditController.IsEnabled = False

    End Sub

    Private Sub LoadPhoneNumbers(ByVal PersonId As Long)
        'Dim myData As DataTable
        Dim DB As New Global_Visas_Data_Layer.DataAccess()
        'myData = DB.GetSQLDataTable()
        DataBinding.BindListView(Global_Visas_Business_Layer.PrivateIndividual.GetPhoneNumbersSQL(PersonId), Me.lvwPhoneNumbers)
        Me.lvwPhoneNumbers.SelectedItems.Clear()
        Me.btnEditPhone.IsEnabled = False
        Me.btnMainPhone.IsEnabled = False
        Me.btnFaxPhone.IsEnabled = False
        Me.btnDeletePhone.IsEnabled = False
    End Sub

    Private Sub LoadEmailAddresses(ByVal PersonId As Long)
        'Dim myData As DataTable
        Dim DB As New Global_Visas_Data_Layer.DataAccess()
        'myData = DB.GetSQLDataTable(Global_Visas_Business_Layer.PrivateIndividual.GetEmailAddressSQL(PersonId))
        DataBinding.BindListView(Global_Visas_Business_Layer.PrivateIndividual.GetEmailAddressSQL(PersonId), Me.lvwEmailAddress)
        Me.lvwEmailAddress.SelectedItems.Clear()
        Me.btnEditEmail.IsEnabled = False
        Me.btnMainEmail.IsEnabled = False
        Me.btnDeleteEmail.IsEnabled = False
        Me.btnSendEmail.IsEnabled = False
    End Sub

    Private Sub LoadAddresses(ByVal PersonId As Long)

        Dim intLineID As Integer = -1
        Dim intCtr As Integer
        Dim myData As DataTable
        'Dim DB As New Global_Visas_Data_Layer.DataAccess()
        myData = Global_Visas_Business_Layer.PrivateIndividual.GetPersonAddressSQL(PersonId)

        If Me.lvwAddresses.SelectedItems.Count > 0 Then
            'intLineID = Me.lvwAddresses.SelectedItems(0).Tag
            intLineID = CInt(Me.lvwAddresses.SelectedItems(0).SubItems(0).Text)
        End If

        DataBinding.BindListView(myData, Me.lvwAddresses)

        Me.lvwAddresses.SelectedItems.Clear()
        Me.btnAddressEdit.IsEnabled = False
        Me.btnAddressDel.IsEnabled = False
        Me.btnAddressChangeToCo.IsEnabled = False
        Me.btnInvoiceAddress.IsEnabled = False
        Me.btnCorrespondence.IsEnabled = False

        If intLineID > -1 Then
            For intCtr = 0 To lvwAddresses.Items.Count - 1
                If CInt(Me.lvwAddresses.Items(intCtr).SubItems(0).Text) = intLineID Then
                    Me.lvwAddresses.Items(intCtr).Selected = True
                End If
            Next
        End If

    End Sub

    Private Sub ShowCandidateDetails(ByVal PersonId As Long)

        Dim myPerson As People.PersonInfo = People.GetPerson(PersonId)
        Dim commonFunc As New Global_Visas_Business_Layer.CommonFuncs()
        With myPerson
            Me.lblCandidateName3.Text = .Firstname & " " & .Surname
            Me.lblPersonJob.Text = .JobTitle

            Me.lblPersonDOB.Text = commonFunc.FormatDate(.DOB)

            ' Me.lblPersonAge.Text = Convert.ToInt32(DateDiff(DateInterval.Year, .DOB, Date.Today))
            Me.lblPersonAge.Text = commonFunc.GetAge(.DOB)
            If Me.lblPersonAge.Text > 200 Then
                Me.lblPersonAge.Text = ""
            End If
            Me.lblPersonQualification.Text = .Qualification
            Me.lblPersonSalary.Text = .Salary
            Me.lblPersonPassportNo.Text = .PassportNo
            Me.lblPersonPassportExp.Text = commonFunc.FormatDate(.PassportExp)
            Me.lblPersonDest.Text = .DestinationName
            Me.lblPersonNat.Text = .NationalityName
            Me.lblPersonRes.Text = .ResidenceName
            Me.lblPersonUKVisa.Text = .UKVisaName
            Me.lblPersonVisaExp.Text = commonFunc.FormatDate(.UKVisaExpiry)
            'Me.lblPersonAccMan.Content = CommonDataFunctions.GetConsultantName(.AccountManagerId)
            Me.lblPersWhereHeard.Content = .WhereHeard
            Me.lblSkillOcc.Text = .SkillOccupationName
        End With

        If myPerson.SkilledOccupationId > 0 Then
            Me.lblSkillOcc.Visibility = True
            Me.lblSkillOccLbl.Visibility = True
        Else
            Me.lblSkillOcc.Visibility = False
            Me.lblSkillOccLbl.Visibility = False
        End If

    End Sub

    Private Sub LoadCompanyInfo()

        Dim myComp As Company.CompanyInfo = Company.GetCompany(GlobalCRM.CurrentCompanyID)

        With myComp
            Me.lblCompanyID.Content = .CompanyID
            Me.lblCompanyName.Content = .CompanyName
            Me.lblCompanySize.Content = .CompanySize
            Me.lblDateEntered.Content = .DateEntered
            Me.lblEnteredBy.Content = .EnteredBy
            Me.lblIndustry.Content = .IndustryName
            Me.lblWebsite.Content = .Website
            Me.lblAccManager.Content = .AccountManager
            Me.lblDefCW.Content = .DefaultCaseWorker

            Me.lblCandidateName.Text = .CompanyName
            Me.lblCandidateID.Text = .CompanyID
            Me.lblAccType.Content = .AccountType
            Me.lblCompanyStatus.Content = .CompanyStatus

            Me.lblWhereHeard.Content = Company.GetCompanyWhereHeard(.CompanyID)

            If .ParentCompanyId > 0 Then
                Me.grpParent.Visibility = True
                Me.lblParentCompId.Content = .ParentCompanyId
                Me.lblParentCompName.Content = Company.GetCompany(.ParentCompanyId).CompanyName
            Else
                Me.grpParent.Visibility = False
            End If

        End With

    End Sub

    Private Sub LoadCompanyAddresses()
        Dim intLineID As Integer = -1
        Dim intCtr As Integer

        If Me.lvwCoAddresses.Items.Count > 0 Then
            'intLineID = Me.lvwAddresses.SelectedItems(0).Tag
            If Me.lvwCoAddresses.SelectedItems.Count > 0 Then
                intLineID = CInt(Me.lvwCoAddresses.SelectedItems(0).SubItems(0).Text)
            End If
        End If
        Dim corporateAddresses As DataTable
        'dim strCorporateAddresses As String = Company.GetCorporateAddresses(GlobalCRM.CurrentCompanyID)
        corporateAddresses = Company.GetCorporateAddresses(GlobalCRM.CurrentCompanyID)
        DataBinding.BindListView(corporateAddresses, Me.lvwCoAddresses)

        If intLineID > -1 Then
            For intCtr = 0 To lvwCoAddresses.Items.Count - 1
                If CInt(Me.lvwCoAddresses.Items(intCtr).SubItems(0).Text) = intLineID Then
                    Me.lvwCoAddresses.Items(intCtr).Selected = True
                End If
            Next
        End If
    End Sub

    Private Sub btnWebLogin_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnWebLogin.Click
        Dim WebForm As New frmWebLogin()
        WebForm.PersonId = lblCandidateId3.Text
        WebForm.ShowDialog()
    End Sub

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            Dim SearchForm As New frmSearch()
            SearchForm.ShowDialog()
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.btnSearch_Click", False)
        End Try
    End Sub

    Private Sub btnDocStore_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDocStore.Click
        Dim frmdocstore As New frmDocumentStore
        frmdocstore.ShowDialog()
    End Sub

    Private Sub btnAddtoCompany_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddtoCompany.Click
        Dim frmAddPersonToCompany As New frmAddPersonToCompany
        frmAddPersonToCompany.ShowDialog()
    End Sub

    Private Sub btnAddPyPlan_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddPyPlan.Click
        Dim frmPaymentPlan As New frmPaymentPlan
        frmPaymentPlan.ShowDialog()
    End Sub

    Private Sub btnRemoveSubsid_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRemoveSubsid.Click

        If MsgBox("Are you sure you want to remove '" & Me.lvwSubsidiary.SelectedItem.row.itemarray(1).ToString & "' as a subsidiary?", vbYesNo + vbExclamation, "Confirm Delete") <> MsgBoxResult.Yes Then
            Exit Sub
        End If

        If Company.RemoveSubsidiary(GlobalCRM.CurrentCompanyID, GlobalCRM.CurrentCompanyName, Me.lvwSubsidiary.SelectedItem.row.itemarray(0).ToString, Me.lvwSubsidiary.SelectedItem.row.itemarray(1).ToString) Then
            DataBinding.BindListView(CommonDataFunctions.SubsidiaryList(GlobalCRM.CurrentCompanyID), Me.lvwSubsidiary)
        End If

    End Sub

    Private Sub btnEditCompany_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditCompany.Click
        Dim frmCompanyDetails As New frmCompanyDetails
        frmCompanyDetails.ShowDialog()
        Me.LoadCompanyInfo()
    End Sub

    Private Sub btnAddCompEvent_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddCompEvent.Click
        Dim frmAddEvent As New frmAddEvent
        Try

            With frmAddEvent
                .EventType = TasksEvents.EventTypes.EventCompany
                .LinkId = GlobalCRM.CurrentCompanyID
                .ShowDialog()
            End With

            Me.RefreshEventList()
        Catch ex As Exception

        Finally
            frmAddEvent = Nothing
        End Try
    End Sub

    Private Sub btnCompanyEvents_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCompanyEvents.Click
        Me.TabControl1.SelectedItem = Me.tabEvent
        Me.radEventCompany.IsChecked = True
    End Sub

    Private Sub btnCompanyAdverts_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCompanyAdverts.Click
        MsgBox("This facility has not been added yet.")
    End Sub

    Private Sub btnEditSLA_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditSLA.Click
        Dim frmSLACharges As New frmSLACharges

        frmSLACharges.ShowDialog()
    End Sub

    Private Sub btnAddSubsidiary_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddSubsidiary.Click
        Dim frmAddCompanyLink As New frmAddCompanyLink
        With frmAddCompanyLink
            .ScreenMode = frmAddCompanyLink.LinkMode.Subsidiary
            .ShowDialog()
        End With
        DataBinding.BindListView(CommonDataFunctions.SubsidiaryList(GlobalCRM.CurrentCompanyID), Me.lvwSubsidiary)
    End Sub

    Private Sub btnSetParentCompany_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSetParentCompany.Click
        Dim frmAddCompanyLink As New frmAddCompanyLink
        With frmAddCompanyLink
            .ScreenMode = frmAddCompanyLink.LinkMode.Parent
            .ShowDialog()
        End With
        DataBinding.BindListView(CommonDataFunctions.SubsidiaryList(GlobalCRM.CurrentCompanyID), Me.lvwSubsidiary)
        Me.LoadCompanyInfo()
    End Sub

    Private Sub btnAddPersToComp_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddPersToComp.Click
        Dim frmAddPerson As New frmAddPerson
        frmAddPerson.ShowDialog()
        DataBinding.BindListView(Company.GetCorporateContacts(GlobalCRM.CurrentCompanyID), Me.lvwContacts)
        DataBinding.BindListView(Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.All), Me.lvwPeopleList)
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddCoAddress.Click
        'Dim frmAddAddress As New frmAddAddress
        'With frmAddAddress
        '    .AddressType = People.AddressTypes.Company
        '    .Content = "Add New Address"
        '    .Address1.drpCountry.DisplayMember = "country_name"
        '    .Address1.drpCountry.ValueMember = "country_id"
        '    .Address1.drpCountry.DataSource = CommonSQL.CountryList
        '    .Address1.drpCountry.SelectedIndex = -1
        '    .ShowDialog()
        'End With

        ''frmAddAddress.AddressType = People.AddressTypes.Company
        ''frmAddAddress.ShowDialog()

        'Me.LoadCompanyAddresses()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditCoAddress.Click
        'Dim frmAddAddress As New frmAddAddress
        'If Me.lvwCoAddresses.SelectedItems.Count = 0 Then
        '    MsgBox("No address selected.")
        '    Exit Sub
        'End If

        'With frmAddAddress
        '    .AddressType = People.AddressTypes.Company
        '    .AddressLinkId = Me.lvwCoAddresses.SelectedItems(0).SubItems(0).Text
        '    .Content = "Edit Address"
        '    .Address1.drpCountry.DisplayMember = "country_name"
        '    .Address1.drpCountry.ValueMember = "country_id"
        '    .Address1.drpCountry.DataSource = CommonSQL.CountryList
        '    .ShowDialog()
        'End With

        'Me.LoadCompanyAddresses()
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCoCorrAddress.Click
        If Me.lvwCoAddresses.SelectedItems.Count = 0 Then
            MsgBox("No address selected.", , "Address")
            Exit Sub
        End If

        If Company.SetCorrespOrInvAddress(Me.lvwCoAddresses.SelectedItems(0).SubItems(0).Text, GlobalCRM.CurrentCompanyID, Me.lvwCoAddresses.SelectedItems(0).SubItems(3).Text.ToString, Company.AddressLinkTypes.Correspondence, Me.lvwCoAddresses.SelectedItems(0).SubItems(4).Text) = True Then
            Me.LoadCompanyAddresses()
        End If
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDelCoAddress.Click
        If Me.lvwCoAddresses.SelectedItems.Count = 0 Then
            Exit Sub
        End If

        If People.DeleteAddress(Me.lvwCoAddresses.SelectedItems(0).SubItems(0).Text, People.AddressTypes.Company) Then
            Me.LoadCompanyAddresses()
        End If
    End Sub

    Private Sub lvwCoAddresses_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles lvwCoAddresses.SelectionChanged

        If Me.lvwCoAddresses.SelectedItems.Count > 0 Then
            Me.btnEditCoAddress.isEnabled = True
            Me.btnDelCoAddress.isEnabled = True
            Me.btnCoInvAddress.isEnabled = True
            Me.btnCoCorrAddress.isEnabled = True
        Else
            Me.btnEditCoAddress.isEnabled = False
            Me.btnDelCoAddress.isEnabled = False
            Me.btnCoInvAddress.isEnabled = False
            Me.btnCoCorrAddress.isEnabled = False
        End If

        ' display full address
        If Me.lvwCoAddresses.SelectedItems.Count > 0 Then
            Dim myAddress As People.AddressInfo = People.GetAddress(Me.lvwCoAddresses.SelectedItems(0).SubItems(0).Text)
            Dim sbAddress As New StringBuilder
            sbAddress.Append(myAddress.AddressText & vbCrLf)
            sbAddress.Append(myAddress.Region & vbCrLf)
            sbAddress.Append(myAddress.Postcode & vbCrLf)
            sbAddress.Append(myAddress.CountryName)
            lblCoAddressFull.Content = sbAddress.ToString
        End If
    End Sub


    Private Sub btnAddEventPerson_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddEventPerson.Click
        Dim frmAddEvent As New frmAddEvent
        If GlobalCRM.CurrentCandidateID > 0 Then
            frmAddEvent.EventType = TasksEvents.EventTypes.EventPerson
            frmAddEvent.LinkId = Me.lblCandidateId3.Text.ToString
            frmAddEvent.ShowDialog()
        End If

        Me.RefreshEventList()
    End Sub

    Private Sub btnViewEventPerson_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnViewEventPerson.Click
        If GlobalCRM.CurrentCandidateID > 0 Then
            Me.TabControl1.SelectedItem = Me.tabEvent
            Me.radEventPerson.IsChecked = True
        End If
    End Sub

    Private Sub btnEditPerson_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditPerson.Click
        Dim frmEditPerson As New frmEditPerson
        Try

        
            If GlobalCRM.CurrentCandidateID > 0 Then
                frmEditPerson.ShowDialog()
                Me.ShowCandidateDetails(Me.ActivePersonId)

            End If

        Catch ex As Exception
        Finally

            frmEditPerson = Nothing
        End Try
    End Sub

    Private Sub btnAddPhone_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddPhone.Click
        Dim frmAddPhone As New frmAddPhone
        Try
            frmAddPhone.ShowDialog()
            frmAddPhone.Content = "Add Phone Number"
            Me.LoadPhoneNumbers(Me.ActivePersonId)
        Catch ex As Exception
        Finally

            frmAddPhone = Nothing
        End Try
    End Sub

    Private Sub btnEditPhone_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditPhone.Click
        Dim frmAddPhone As New frmAddPhone
        Try


            With frmAddPhone
                .Content = "Edit Phone Number"
                .PhoneId = Me.lvwPhoneNumbers.SelectedItems(0).SubItems(0).ToString
                .txtPhoneNumber.Text = Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString
                .txtPhoneTitle.Text = Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString
                .ShowDialog()
            End With
            Me.LoadPhoneNumbers(Me.ActivePersonId)
        Catch ex As Exception
            frmAddPhone = Nothing
        End Try
    End Sub

    Private Sub btnMainPhone_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnMainPhone.Click

        If Me.lvwPhoneNumbers.SelectedItems.Count = 0 Then
            MsgBox("Please select a phone number first!", MsgBoxStyle.Exclamation, "Select")
            Exit Sub
        Else
            Select Case Me.lvwPhoneNumbers.SelectedItem.row.itemarray(3).ToString

                Case "Main", "Both"
                    'Is already set to main
                    Call MsgBox("Already set as the main number!", MsgBoxStyle.Exclamation, "Main Number")
                    Exit Sub

                Case "Fax"
                    'Set to both
                    People.SetMainOrFaxPhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, People.PhoneTypes.PhoneBoth, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                    Me.LoadPhoneNumbers(Me.ActivePersonId)

                Case Else
                    'Not set, so set to main
                    People.SetMainOrFaxPhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, People.PhoneTypes.PhoneMain, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                    Me.LoadPhoneNumbers(Me.ActivePersonId)

            End Select
        End If
    End Sub

    Private Sub btnFaxPhone_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnFaxPhone.Click
        If Me.lvwPhoneNumbers.SelectedItems.Count = 0 Then
            MsgBox("Please select a phone number first!", MsgBoxStyle.Exclamation, "Phone/Fax")
            Exit Sub
        Else
            Select Case Me.lvwPhoneNumbers.SelectedItem.row.itemarray(3).ToString

                Case "Fax", "Both"
                    'Is already set to Fax
                    Call MsgBox("Already set as the Fax number!", MsgBoxStyle.Exclamation, "Fax Number")
                    Exit Sub

                Case "Main"
                    'Set to both
                    People.SetMainOrFaxPhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, People.PhoneTypes.PhoneBoth, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                    Me.LoadPhoneNumbers(Me.ActivePersonId)

                Case Else
                    'Not set, so set to fax
                    People.SetMainOrFaxPhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, People.PhoneTypes.PhoneFax, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                    Me.LoadPhoneNumbers(Me.ActivePersonId)

            End Select
        End If
    End Sub

    Private Sub btnDeletePhone_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDeletePhone.Click

        If Me.lvwPhoneNumbers.SelectedItems.Count = 0 Then
            MsgBox("Please select a phone number first!", MsgBoxStyle.Exclamation, "Delete Phone")
            Exit Sub
        ElseIf Me.lvwPhoneNumbers.Items.Count = 1 Then
            If MsgBox("This is the only number listed for this person, are you sure you want to delete it?", vbYesNo + vbExclamation, "Confirm Delete") = MsgBoxResult.Yes Then
                People.DeletePhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                Me.LoadPhoneNumbers(Me.ActivePersonId)
            Else
                Exit Sub
            End If
        Else
            If Me.lvwPhoneNumbers.SelectedItem.row.itemarray(3).ToString = "Main" Then
                'Refuse to delete
                MsgBox("That is the main number for this person, please select another number as the main number before deleting this one.", MsgBoxStyle.Exclamation, "Main Number")
                Exit Sub
            Else
                If MsgBox("Are you sure you want to delete the phone number " & Me.lvwPhoneNumbers.SelectedItems(0).SubItems(2).Text & "?", vbYesNo + vbExclamation, "Confirm Delete") = MsgBoxResult.Yes Then
                    People.DeletePhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                    Me.LoadPhoneNumbers(Me.ActivePersonId)
                End If
            End If
        End If
    End Sub

    Private Sub btnAddEmail_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddEmail.Click
        Dim frmAddEmail As New frmAddEmail
        Try

        
            frmAddEmail.ShowDialog()
            frmAddEmail.Content = "Add Email Address"
            Me.LoadEmailAddresses(Me.ActivePersonId)
        Catch ex As Exception
        Finally
            frmAddEmail = Nothing
        End Try

    End Sub

    Private Sub btnEditEmail_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditEmail.Click
        Dim frmAddEmail As New frmAddEmail
        Try
            With frmAddEmail
                .EMailId = Me.lvwEmailAddress.SelectedItems(0).SubItems(0).Text
                .Content = "Edit Email Address"
                .txtEmailAddress.Text = Me.lvwEmailAddress.SelectedItem.row.itemarray(2).ToString
                .cboDescription.Text = Me.lvwEmailAddress.SelectedItem.row.itemarray(1).ToString
                .ShowDialog()
            End With
            Me.LoadEmailAddresses(Me.ActivePersonId)
        Catch ex As Exception
        Finally
            frmAddEmail = Nothing
        End Try

    End Sub

    Private Sub btnMainEmail_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnMainEmail.Click

        If Me.lvwEmailAddress.SelectedItems.Count = 0 Then
            MsgBox("Please select an email address first!", MsgBoxStyle.Exclamation, "Select Email Address")
            Exit Sub
        End If

        If Me.lvwEmailAddress.SelectedItem.row.itemarray(3).ToString = "Main" Then
            MsgBox("Already set as main address!", MsgBoxStyle.Exclamation, "Email Address")
            Exit Sub
        End If

        If People.SetMainEmailAddress(Me.lvwEmailAddress.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwEmailAddress.SelectedItem.row.itemarray(1).ToString, Me.lvwEmailAddress.SelectedItem.row.itemarray(2).ToString) Then
            Me.LoadEmailAddresses(Me.ActivePersonId)
        End If

    End Sub

    Private Sub btnDeleteEmail_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDeleteEmail.Click
        If Me.lvwEmailAddress.SelectedItems.Count = 0 Then
            MsgBox("Please select an email address first!", MsgBoxStyle.Exclamation, "Email Address")
            Exit Sub
        ElseIf Me.lvwEmailAddress.Items.Count = 1 Then
            If MsgBox("This is the only email address listed for this person, are you sure you want to delete it?", vbYesNo + vbExclamation, "Confirm Delete") = MsgBoxResult.Yes Then
                If People.DeleteEmailAddress(Me.lvwEmailAddress.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwEmailAddress.SelectedItem.row.itemarray(1).ToString, Me.lvwEmailAddress.SelectedItem.row.itemarray(2).ToString) Then
                    Me.LoadEmailAddresses(Me.ActivePersonId)
                End If
            Else
                Exit Sub
            End If
        Else
            If Me.lvwEmailAddress.SelectedItems(0).SubItems(3).Text = "Main" Then
                'Refuse to delete
                MsgBox("That is the main email address for this person, please select another email as the main email before deleting this one.", MsgBoxStyle.Exclamation, "Mail Email Address")
                Exit Sub
            Else
                If MsgBox("Are you sure you want to delete the email address " & Me.lvwEmailAddress.SelectedItem.row.itemarray(2).ToString & "?", vbYesNo + vbExclamation, "Confirm Delete") = MsgBoxResult.Yes Then

                    If People.DeleteEmailAddress(Me.lvwEmailAddress.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwEmailAddress.SelectedItem.row.itemarray(1).ToString, Me.lvwEmailAddress.SelectedItem.row.itemarray(2).ToString) Then
                        Me.LoadEmailAddresses(Me.ActivePersonId)
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub btnAddressAdd_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddressAdd.Click
        Dim frmAddAddress As New frmAddAddress
        Try

        
            With frmAddAddress
                .AddressType = People.AddressTypes.Person
                .Content = "Add New Address"
                '.Address1.drpCountry.DisplayMember = "country_name"
                '.Address1.drpCountry.ValueMember = "country_id"
                '.Address1.drpCountry.DataSource = CommonSQL.CountryList
                '.Address1.drpCountry.SelectedIndex = -1
                .ShowDialog()
            End With
            Me.LoadAddresses(Me.ActivePersonId)
        Catch ex As Exception
        Finally
            frmAddAddress = Nothing

        End Try
    End Sub

    Private Sub btnAddressEdit_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddressEdit.Click
        Dim frmAddAddress As New frmAddAddress
        Try

        
            If lvwAddresses.SelectedItems.Count > 0 Then
                With frmAddAddress
                    .AddressType = People.AddressTypes.Person
                    .AddressLinkId = Me.lvwAddresses.SelectedItems(0).SubItems(0).Text
                    '.Text = "Edit Address"
                    '.Address1.drpCountry.DisplayMember = "country_name"
                    '.Address1.drpCountry.ValueMember = "country_id"
                    '.Address1.drpCountry.DataSource = CommonSQL.CountryList
                    .ShowDialog()
                    '.AddressType = People.AddressTypes.Person
                    '.AddressLinkId = Me.lvwAddresses.SelectedItems(0).SubItems(0).Text
                    '.Text = "Edit Address"
                    '.Address1.txtDescription.Text = Me.lvwAddresses.SelectedItems(0).SubItems(2).Text
                    '.Address1.txtAddress.Text = Me.lvwAddresses.SelectedItems(0).SubItems(4).Text
                    '.ShowDialog()
                End With
                Me.LoadAddresses(Me.ActivePersonId)
            Else
                MsgBox("No address selected.", , "Address")
            End If
        Catch ex As Exception
        Finally
            frmAddAddress = Nothing
        End Try
    End Sub

    Private Sub btnAddressDel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddressDel.Click

        If Me.lvwAddresses.SelectedItems.Count = 0 Then
            Exit Sub
        End If

        If People.DeleteAddress(Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString, People.AddressTypes.Person, GlobalCRM.CurrentCandidateName) Then
            Me.LoadAddresses(Me.ActivePersonId)
        End If
    End Sub

    Private Sub btnCorrespondence_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCorrespondence.Click

        Dim ChangeTo As People.AddressLinkTypes

        If Me.lvwAddresses.SelectedItems.Count = 0 Then
            MsgBox("Please select an address first", MsgBoxStyle.Exclamation, "Select Address")
            Exit Sub
        End If

        If Me.lvwAddresses.SelectedItem.row.itemarray(3).ToString = "Cor" Or Me.lvwAddresses.SelectedItem.row.itemarray(3).ToString = "Both" Then
            MsgBox("This is already marked as the correspondence address", MsgBoxStyle.Exclamation, "Correspondence Address")
            Exit Sub
        End If

        If Me.lvwAddresses.SelectedItem.row.itemarray(3).ToString = "Inv" Then
            ChangeTo = People.AddressLinkTypes.Both
        Else
            ChangeTo = People.AddressLinkTypes.Correspondence
        End If

        If People.SetCorrespOrInvAddress(Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwAddresses.SelectedItem.row.itemarray(1).ToString, ChangeTo) Then
            Me.LoadAddresses(Me.ActivePersonId)
        End If
    End Sub

    Private Sub btnInvoiceAddress_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnInvoiceAddress.Click

        Dim ChangeTo As People.AddressLinkTypes

        If Me.lvwAddresses.SelectedItems.Count = 0 Then
            MsgBox("Please select an address first", MsgBoxStyle.Exclamation, "Select Address")
            Exit Sub
        End If

        If Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString = "Inv" Or Me.lvwAddresses.SelectedItem.row.itemarray(3).ToString = "Both" Then
            MsgBox("This is already marked as the invoice address", MsgBoxStyle.Exclamation, "Invoice Address")
            Exit Sub
        End If

        If Me.lvwAddresses.SelectedItem.row.itemarray(3).ToString = "Cor" Then
            ChangeTo = People.AddressLinkTypes.Both
        Else
            ChangeTo = People.AddressLinkTypes.Invoice
        End If

        If People.SetCorrespOrInvAddress(Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwAddresses.SelectedItem.row.itemarray(1).ToString, ChangeTo) Then
            Me.LoadAddresses(Me.ActivePersonId)
        End If
    End Sub

    Private Sub btnAddressChangeToCo_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddressChangeToCo.Click

        Dim CompAddr As String

        If Me.lvwAddresses.SelectedItems.Count = 0 Then
            MsgBox("Please select an address first", MsgBoxStyle.Exclamation, "Select Address")
            Exit Sub
        End If

        If Me.lvwAddresses.SelectedItem.row.itemarray(2).ToString = "Co" Then
            MsgBox("This is already a company address", MsgBoxStyle.Exclamation, "Company Address")
            Exit Sub
        End If

        CompAddr = InputBox("Please enter the name you wish the address to have with the company", "Send Address to Company", Me.lvwAddresses.SelectedItem.row.itemarray(1).ToString)

        If CompAddr.Trim = "" Then
            MsgBox("Cannot have a blank name", MsgBoxStyle.Exclamation, "Blank Name")
            Exit Sub
        End If

        If People.SetAddressAsCompany(Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentConName, GlobalCRM.CurrentCompanyID, CompAddr.Trim) Then
            Me.LoadAddresses(Me.ActivePersonId)
            Me.LoadCompanyAddresses()
        End If
    End Sub

    Private Sub btnWeb_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnWeb.Click
        Dim strWebAddress As String = Me.lblWebsite.Content

        If Mid(strWebAddress, 1, 7) = "http://" Then
            ' do nothing
        Else
            strWebAddress = "http://" & strWebAddress
        End If

        System.Diagnostics.Process.Start(strWebAddress)
    End Sub

    Private Sub btnDepend_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDepend.Click
        Dim frmDependants As New frmDependants
        Try

        
            frmDependants.ShowDialog()

            ' grab current person for later
            Dim PersonID As Long = GlobalCRM.CurrentCandidateID

            If frmDependants._AddNewPerson Then
                frmDependants.Close()
                Dim frmAddPerson As New frmAddPerson
                Try

                
                    With frmAddPerson
                        'Form_Fm_AddPerson.Txt_CompanyID.Visible = False
                        .drpRelationship.Visibility = False

                        'Where Hear value will be set to 'Dependant' automaticaly
                        .grpAdvert.Visibility = False

                        ' xxx you need to sort out passing the Dependents ID to the add person form
                        ' xxx add a label on the add person form and pass this value to it
                        ' xxx then pick up the value from label when user clicks on Save button
                        ._Dependant = GlobalCRM.CurrentCandidateID

                        .grpDependentOf.Visibility = True
                        .lblParentID.Visibility = True
                        .lblParentID.Content = GlobalCRM.CurrentCandidateID
                        .lblParentDesc.Visibility = True
                        .lblParentDesc.Content = GlobalCRM.CurrentDependentParentDescription
                        .lblChildDesc.Visibility = True
                        .lblChildDesc.Content = GlobalCRM.CurrentDependentChildDescription

                        .ShowDialog()

                        frmDependants.Close()

                        ' return to current person (otherwise added person becomes the current person)
                        GlobalCRM.CurrentCandidateID = PersonID

                    End With
                Catch ex As Exception

                End Try
            Else
                frmDependants.Close()
            End If

            ' refresh dependants
            DataBinding.BindListView(People.GetDependants(GlobalCRM.CurrentCandidateID), Me.lvwDepend)
        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnCreditController_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCreditController.Click
        Dim tsk As New TasksEvents
        Try

        
            Dim caseid As Long = GlobalCRM.CurrentCaseID

            'Dim PaidAmt, GrossInv As Object
            Dim writeoffamount As Double
            'Dim dt As DataTable
            'Dim row As DataRow

            If MsgBox("Are you sure you want to write off the case : " & caseid, MsgBoxStyle.YesNo, "WriteOff") = MsgBoxResult.Yes Then

                'Dim i As Integer
                Dim blnWrittenoff As Boolean = False

                blnWrittenoff = False
                caseid = GlobalCRM.CurrentCaseID
                GlobalCRM.CurrentCaseID = caseid
                Dim statusid As Long
                statusid = CInt(CommonDataFunctions.GetStatusFromCase(caseid))
                If statusid = 2000 Then
                    MsgBox("The case has already been written off", MsgBoxStyle.Critical, "Already Written Off")

                    Exit Sub
                End If
                If CommonDataFunctions.WriteOffFinance(caseid) = True Then
                    If MsgBox("Would you like to close the case now?", MsgBoxStyle.YesNo, "Close the case?") = MsgBoxResult.Yes Then
                        Dim status As String = CommonDataFunctions.getCaseStageTitle(caseid)
                        If status <> "" Then
                            CommonDataFunctions.UpdateCaseStatus(status, "Written-Off")
                            CommonDataFunctions.UpdateCaseStatusNo(statusid, 2000)
                        End If
                       
                        If CommonDataFunctions.UpdateStatusAsWriteoff(caseid) = True Then
                            CommonDataFunctions.CompleteTasksForCase(caseid)
                            tsk.GblFunc_Add_Event("File Written Off", "The file has been written off by : " & GlobalCRM.CurrentConName, TasksEvents.EventStatus.SingleEvent, caseid, TasksEvents.EventTypes.EventCase)
                            MsgBox("The case " & caseid & "  has been written off successfully.", MsgBoxStyle.Information, "Success")

                        Else
                            MsgBox("There was an error in writing off the case " & caseid & "  .Please contact IT", MsgBoxStyle.Information, "Error")
                        End If
                    End If
                    'refresh main page
                    SelectedCaseChanged()
                End If

            Else
                MsgBox("There was an error in writing off the case. Please contact IT", MsgBoxStyle.Critical, "Write Off")
            End If
            MsgBox("Amount to be written off : " & writeoffamount, MsgBoxStyle.Information, "Write off")
        Catch ex As Exception
        Finally
            tsk = Nothing
        End Try
    End Sub
   
    Private Sub btnRevertWriteOff_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRevertWriteOff.Click
        If CommonFuncs.ISCaseWrittenOff(GlobalCRM.CurrentCaseID) = True Then
            Dim frmrevertWriteOff As New frmrevertWriteOff
            frmrevertWriteOff.ShowDialog()
            SelectedCaseChanged()
        Else
            MsgBox("The case has already been written off, Please try a different case", MsgBoxStyle.Critical, "Case Already Written-Off")
        End If
    End Sub

    Private Sub btnViewCaseEvents_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnViewCaseEvents.Click
        Me.TabControl1.SelectedItem = Me.tabEvent
        Me.radEventCase.IsChecked = True
    End Sub

    Private Sub btnAddCaseEvent_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddCaseEvent.Click
        Dim frmAddEvent As New frmAddEvent
        Try

        
            frmAddEvent.EventType = TasksEvents.EventTypes.EventCase
            frmAddEvent.LinkId = GlobalCRM.CurrentCaseID
            frmAddEvent.ShowDialog()
            Me.RefreshEventList()
        Catch ex As Exception
        Finally
            frmAddEvent = Nothing
        End Try
    End Sub

    Private Sub btnStockLetters_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnStockLetters.Click
        Dim frmStockLetters As New frmStockLetters
        frmStockLetters.ShowDialog()
        frmStockLetters = Nothing
    End Sub

    Private Sub btnInbox_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnInbox.Click
        Dim frmMailbox As New frmMailbox
        'frmMailbox.MdiParent = frmMDIMain
        frmMailbox.Show()
        frmMailbox = Nothing
    End Sub

    Private Sub btnEditCase_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditCase.Click
        Dim frmEditCase As New frmEditCase

        frmEditCase.ShowDialog()
        Me.CaseViewChanged(Me, New System.EventArgs)
        Me.SelectActiveCase()
    End Sub
    Private Sub SelectActiveCase()
        'Dim myRow As Xceed.Grid.CellRow   ' DataGridViewRow

        'Me.grdCases.SelectedRows.Clear()

        'For Each myRow In Me.grdCases.DataRows
        '    If myRow.Cells(0).Value = GlobalCRM.CurrentCaseID Then
        '        Me.grdCases.SelectedRows.Add(myRow)
        '        AddRegValue(GlobalCRM.CurrentCaseID)
        '        Exit For

        '    Else



        '    End If
        'Next


    End Sub
End Class
